Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The while loop should end after reading the third line in my file but why does it run the fourth time?

void Load_from_file()
    {
        ifstream fin("Data.txt");
        //fin.open("Data.txt");
        if (!fin.is_open())
            cout << "Error while opening the file" << endl;
        else
        {
            int f_id;
            int u_id;
            int priority;
            char acc_type;
            char delim;
            while (!fin.eof())
            {
                
                fin >> f_id;
                fin >> delim; // skipping the comma
                fin >> u_id;
                fin >> delim;
                fin >> priority;
                fin >> delim;
                fin >> acc_type;
            }
            fin.close();
        }
    }

Data in the file is :

7551,10,3,R
25551,3,10,W
32451,4,7,R


The while loop should end after third iteration but it terminates after fourth iteration

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is the condition in the while statement

        while (!fin.eof())
        {
            
            fin >> f_id;
            fin >> delim; // skipping the comma
            fin >> u_id;
            fin >> delim;
            fin >> priority;
            fin >> delim;
            fin >> acc_type;
        }

The condition fin.eof() can occur within the body of the while loop after already reading the last data.

Either you need to write

        while (fin >> f_id >> delim >> u_id >> delim >>
               priority >> delim >> acc_type );

Or it would be much better to read a whole line and then using the string stream to enter various data like

while ( std::getline( fin, line ) )
{
    std::istringstream iss( line );
    
    iss >> f_id;
    // and so on
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading