file read and display

closed account (1vf9z8AR)
Code inputs values but displays only last name 3 times and all roll numbers displayed are 0.

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
 #include<iostream>
#include<fstream>
using namespace std;
int main()
{
          char name[80];
    int rno;

    ofstream w;
    w.open("test.txt");
    for(int i=1;i<=3;i++)
    {
        cout<<"Enter student "<<i<<"details"<<endl;
        cout<<"Name(dot to end input):";cin.getline(name,80,'.');cout<<endl;
        cout<<"Roll number:";cin>>rno;cout<<endl;
        w<<name;
        w<<rno;
    }
    w.close();

    ifstream r;
    r.open("test.txt");
    r.seekg(0);
    for(int i=1;i<=3;i++)
    {
        r>>rno;
        r>>name;
        cout<<"Displaying student details"<<endl;
    cout<<"Name:"<<name<<endl;
    cout<<"Roll number"<<rno<<endl;
    }
    r.close();
}
Last edited on
What's in the file test.txt when you're finished?
I might do it something like this. I made a number of changes, in particular, no need to end the name with a dot, separate the items in the file so they are readable, don't use a for-loop to try to guess how many items are in the file, just read it until there is no more data. Also, no need to declare the stream separately before opening it, do it in one go.

Some of the changes were just in formatting the output which may be considered cosmetic and not important.

However in the C++ code itself, I tend to like a reasonable amount of whitespace around operators such as >> and << otherwise, the code merges into a single block and isn't so easy (at least for me) to read. I also usually prefer the newline character '\n' rather than endl unless there is some specific reason why the stream needs to be flushed.

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string name;
    int rno;

    ofstream w("test.txt");

    for (int i=1; i<=3; i++)
    {
        cout << "\nEnter student " << i << " details\n\n";
        cout << "       Name: ";
        getline(cin, name);
        cout << "Roll number: ";
        cin  >> rno;
        cin.ignore(1000, '\n');
        w << name << '\t' << rno << '\n';
    }
    w.close();

    ifstream r("test.txt");
    cout << "\n\nDisplaying student details\n\n";

    while ( getline(r, name, '\t') && r >> rno)
    {
        r.ignore(1000, '\n');
        cout << "       Name: " << name << '\n'
             << "Roll number: " << rno  << "\n\n";
    }
    r.close();
}

Last edited on
closed account (1vf9z8AR)
ooooh thanks.while loop is so much better
Topic archived. No new replies allowed.