HadyZn
HadyZn

Reputation: 17

Reading text file c++ (not able to display other lines)

    char fname[20];
    char lname[20];
    int grade[10];
    double avg=0.00;

    fstream infile("C:\\Users\\Hady Zn\\Desktop\\hady.txt", ios::in);
    fstream outfile("C:\\Users\\Hady Zn\\Desktop\\hady1.txt", ios::out);


    while(infile>>fname>>lname)
    {
        outfile<<fname<<" "<<lname<<" ";
        for(int i=0; i<10; i++)
            grade[i]=0; 

    for(int i=0; i<10; i++)
    {

        infile>>grade[i];

        if(grade[i]>=0 && grade[i]<=100)
        {
        outfile<<grade[i]<<" ";
        avg+=grade[i];
        }

    }

    outfile<<avg/10.00<<endl;
    avg=0.00;

    }

So the question is that i need to read from a text file a last name(space) first name(space) then 10 quiz grades(space between each grade) and write the same data into an output file with the average of 10 quizzes at each end of a line. The problem that im facing is that if i had less than 10 quizzes on one line it will not display the remaining lines.(I want it to still give me the average of the grades given considering for example if i was given 7 grades 3 will be zeros) I tried solving it but it just won't work. Any ideas that can solve this? Please help. Thank you

Upvotes: 1

Views: 253

Answers (1)

R Sahu
R Sahu

Reputation: 206737

In order to perform such checks, it's better to read the text from the input file line by line and process each line to extract the data.

string line
while ( getline(infile, line) )
{
   istringstream sstream(line); 
   sstream >> fname >> lname;
   if (!sstream )
   {
      continue;
   }

   outfile<<fname<<" "<<lname<<" ";
   for(int i=0; i<10; i++)
   {
      grade[i]=0; 
      sstream>>grade[i];
      if ( !sstream )
      {
         break;
      }

      if(grade[i]>=0 && grade[i]<=100)
      {
         outfile<<grade[i]<<" ";
         avg+=grade[i];
      }
   }
}

Update, in response to comment by OP:

You can avoid reading the input file line by line and processing each line. Here's my suggested changes to the loop.

while(infile>>fname>>lname)
{
   outfile<<fname<<" "<<lname<<" ";

   for(int i=0; i<10; i++)
   {
      grade[i]=0; 
      infile>>grade[i];
      if ( !infile )
      {
         infile.clear();
         break;
      }

      if(grade[i]>=0 && grade[i]<=100)
      {
         outfile<<grade[i]<<" ";
         avg+=grade[i];
      }
   }

   outfile<<avg/10.00<<endl;
   avg=0.00;

}

Upvotes: 1

Related Questions