0

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 
laughing
  • 158
  • 13

1 Answers1

3

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";
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • So, based on your first solution, I see it is working fine but I would like to replace the missing score with 0. So the total quiz will be remain 10. Can I do that without using getline? – laughing Apr 28 '20 at 19:07
  • 1
    @laughing, that's a question best answered in a different post. You can use different strategies for that. For example, you can use an array or a vector that are initialized with 0 and replaced by values that you are able to read from the file. – R Sahu Apr 28 '20 at 19:10
  • thank you for your suggestion, that helped me alot. – laughing Apr 28 '20 at 19:12