while (!ourfile.eof) not working

Hi! I'm writing a program to manipulate data from a text file. The text file includes names followed by the data (ints) associated with that name (e.g., "Name1 1 1 2 3 4 Name2 3 2 1 1"). I'm expecting the code below to read in the name and then read all the data until it gets to the next name, and then start over with the next person's name and results. I want it to do this until every participants data has been read. I'm expecting the code below to cout: "Name1 1 1 2 3 4 Name2 3 2 1 1". Instead it couts this: "Name1 1 3 4" and then the window scrolls down infinitely.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
   string filename;
   ifstream ourfile;
   cout << "What file do you want to use?  ";
   cin >> filename;
   ourfile.open(filename.c_str());
   
   while (!ourfile.eof())
   {
        string name;
        ourfile >> name;
        cout << name <<" ";
        int number = 0;
        while (ourfile>>number)
        {
           ourfile >> number;
           cout << number<<" ";
        }
   }
}


Thanks for your help!
After it has failed to read a number the failbit will be set. No read operations will succeed as long as the failbit is set. To unset the failbit you have to call the clear function.
ourfile.clear();

And you should probably not be using eof in the loop condition because the eofbit might be set too late. Instead I would use line 12 as a loop condition. That also handles other kinds of errors better.
Last edited on
I'm still kind of confused. Some questions:

1. So, are you saying the compiler will think it's the end of the file if number fails to read an int? I didn't know they'd be related.

2. Is there a way to read a whole file without using .eof in a while loop?

3. I tried to think how I'd use line 12 instead of .eof, and I couldn't figure it out. Is there any way you can be more specific?

Thanks for your help. Really appreciate it.
For points 2 and 3, ¿didn't you write line 15?

Edit: ¿why are you reading twice (and ignoring the first) in the loop 15-19?
Edit2: `ourfile' is an awful name, consider `input' instead
Last edited on
Thank you so much for your help. I tried to apply what you guys have said and this is what I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   
   string filename;
   ifstream input;
   cout << "What file do you want to use?  ";
   cin >> filename;
   input.open(filename.c_str());

   string name; 
   while (input >> name)   
   {
        cout << name <<" ";
	int number;
        while (input>>number)
        {
           cout << number<<" ";
        }
   }


However, it's only couting "Name1 1 1 2 3 4" instead of "Name1 1 1 2 3 4 Name2 3 2 1 1". What am I not getting. Thanks a bunch.
Just kidding. After I just input.clear(); after the input>>number loop, it worked. Thanks a ton for your guy's help.
Topic archived. No new replies allowed.