1

I am trying to read from a file using a while loop and I am stuck as to why it keeps looping forever. I think it has something to do with my while loop condition but I am unable to figure it out.

#include <iostream>
    #include <fstream>
    #include <cstdlib>
    
    using namespace std;
    
    int main()
    {
        string name;
        int age, favNum;
        
        ifstream inFile;
        inFile.open("Trial.txt");
        if(inFile.fail())
        {
            cout << "No Such File!" << endl;
            exit(100);
        }
        
        cout << "The names are: " << endl;
        while(!inFile.eof())
        {
            getline(inFile, name);
            cout << name << endl;
            
            inFile >> age;
            cout << age << endl;
            
            inFile >> favNum;
            cout << favNum << endl;
            
            inFile.ignore(100, '\n');
        }
        
        inFile.close();
    }

Text File

Joe
10 12
Zoe
20 12
John
19 12
Harold
20 12
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Ron
  • 23
  • 3
  • It doesn't `keeps looping forever` in my computer, are you sure about that? – ABacker Dec 01 '21 at 06:14
  • Yeah for some reason in my laptop it keeps looping forever – Ron Dec 01 '21 at 06:16
  • I tried it on my friends laptop and it does not loop forever on his too, could something be wrong with my laptop? – Ron Dec 01 '21 at 06:19
  • Try clean all the binaries and recompile your program. – ABacker Dec 01 '21 at 06:27
  • 2
    [why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Secundi Dec 01 '21 at 06:45
  • In other words, try using `while(getline(inFile, name) && inFile >> name >> age) {...}` – Arnab De Dec 01 '21 at 08:44

1 Answers1

0

Correct way of reading from file is as follows:

While(infile>>name) Cout <<name<<endl;

Using !inFile.eof as condition is problematic.