laughing
laughing

Reputation: 163

C++ fstream not read the next line from the file

I stuck in reading the text and integer from the file using ifstream with c++.

My goal is to read the firstname and lastname following by 10 quiz score. It is working but if the any quiz score is missing, the program will not read the next line.

ifstream inputStream;
inputStream.open("input2.dat");
if (inputStream.fail() )
{
    cout << "Error opening the file.\n";
    exit(1);
}
ofstream fout;
fout.open("output.dat");
string firstname, lastname;
int quizScore = 0;
double sum = 0;
while (inputStream >> firstname >> lastname) 
{
    sum = 0;
    fout << firstname << ' ' << lastname;
    for (int i = 0; i < 10; i++)
    {
        inputStream >> quizScore;
        sum += quizScore;
        fout << " " << quizScore;
    }
    cout << firstname << "\t" << sum / 10 << "\n";
    fout << " " << sum / 10 << "\n";
}
inputStream.close();
fout.close();

input2.dat

Tony Dinozzo 50 45 40 35 30 15 10 5
Ziva David 50 45 50 45 38 
Timothy Mcgee 15 45 25 45 28 50 35 

Upvotes: 0

Views: 312

Answers (1)

R Sahu
R Sahu

Reputation: 206607

The problem is that if there aren't 10 numbers, the stream goes into an error state and does not read anything else after that. You'll have to clear the error state of the stream before it can read anything more.

while (inputStream >> firstname >> lastname) 
{
    sum = 0;
    fout << firstname << ' ' << lastname;
    for (int i = 0; i < 10; i++)
    {
       // Deal with missing numbers.
       if ( !(inputStream >> quizScore) )
       {
          break;
       }

        sum += quizScore;
        fout << " " << quizScore;
    }

    cout << firstname << "\t" << sum / 10 << "\n";
    fout << " " << sum / 10 << "\n";

    // Clear the error state before reading contents of next line
    inputStream.clear();
}

For programming tasks such as the one you are dealing with, it's best to:

  1. Read the contents of file line by line.
  2. Process each line separately.
std::string line;
while ( getline(inputStream, line) )
{
   std::istringstream str(line);
   str >> firstname >> lastname; 

   sum = 0;
   fout << firstname << ' ' << lastname;
   for (int i = 0; i < 10; i++)
   {
      // Deal with missing numbers.
      if ( !(str >> quizScore) )
      {
         break;
      }

      sum += quizScore;
      fout << " " << quizScore;
   }

   cout << firstname << "\t" << sum / 10 << "\n";
   fout << " " << sum / 10 << "\n";
}

Upvotes: 3

Related Questions