1
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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Change `while (!fin.eof())` to `while(fin >> f_id >> delim >> u_id >> delim >> priority >> delim >> acc_type) {/*do something with the data...?*/}` – Eljay Dec 24 '21 at 17:14
  • @JohnnyMopp yes i get something from that but i am unable to figure out the solution to the problem – Muhammad Arslan Waqar Dec 24 '21 at 17:20

1 Answers1

1

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
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335