text file

closed account (1vf9z8AR)
I am writing the text file in different lines but when read my file it shows in same line
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  #include<iostream>
#include<fstream>
using namespace std;
void write()
{
    char ch,line[80];
    ofstream w1;
    w1.open("text.txt");
    do
    {
        cout<<"Enter line"<<endl;
        cin>>line;
         cout<<endl;
        w1<<line;
        cout<<"\nMore lines?(y/n)"<<endl;
        cin>>ch;
    }while(ch=='y');
    w1.close();
}
void read()
{
    char line[80];
    ifstream r1;
    r1.open("text.txt");
    while(!r1.eof())
    {
        r1>>line;
        cout<<line;
        r1.open("text.txt");
    }
    r1.close();
}
int main()
{
    int n;
    char ch;
    do
    {
    cout<<"1-write file"<<endl;
    cout<<"2-read file"<<endl;
    cout<<"Enter option:";cin>>n;cout<<endl;
    if(n==1)
        write();
    else if(n==2)
        read();
    else
        cout<<"Enter correct option!!"<<endl;
    cout<<"Do you want to continue(y/n)?";cin>>ch;
    cout<<endl;
    }while(ch=='y');
}
Newlines are not read into your string.

A couple of additional notes:

1. Don't loop on EOF.
2. Use getline().
3. Use string.

Also, what is the purpose of line 29? (Don't do that!)

1
2
#include <fstream>
#include <string> 
1
2
3
4
5
6
7
8
  // Read every line of "text.txt" and echo it to stdout, prefixed by the line number:
  std::string s;
  std::ifstream f("text.txt");
  std::size_t n = 0;
  while (std::getline( f, s ))
  {
    cout << (++n) << ": " << s << "\n";
  }

Hope this helps.
closed account (1vf9z8AR)
Here is my edited program but still output in same line
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
#include<fstream>
using namespace std;
void write()
{
    char ch,line[80];
    ofstream w1;
    w1.open("text.txt");
    do
    {
        cout<<"Enter line(dot to terminate)"<<endl;
        cin.getline(line,80,'.');
         cout<<endl;
        w1<<line;
        cout<<"\nMore lines?(y/n)"<<endl;
        cin>>ch;
    }while(ch=='y');
    w1.close();
}
void read()
{
    char line[80];
    ifstream r1;
    r1.open("text.txt");
    while(!r1.eof())
    {
        r1>>line;
        cout<<line;
    }
    r1.close();
}
int main()
{
    int n;
    char ch;
    do
    {
    cout<<"1-write file"<<endl;
    cout<<"2-read file"<<endl;
    cout<<"Enter option:";cin>>n;cout<<endl;
    if(n==1)
        write();
    else if(n==2)
        read();
    else
        cout<<"Enter correct option!!"<<endl;
    cout<<"Do you want to continue(y/n)?";cin>>ch;
    cout<<endl;
    }while(ch=='y');
}
Last edited on
And yet you have not made any of the changes I suggested.
Topic archived. No new replies allowed.