简体   繁体   中英

Read grades from file and output average to another file C++

Hi I have been trying to work on a projedct to read grades from an input file and output the same grades and the average based on the first line which contains the total to another file and I am completely lost. I have tried using getline() function to read in the line of grades displayed as name 7 8 9 10 then use the istringstream to read each value. I can't seem to ge tthe syntax right and my code will only getline every other line of grades and the string outputs all zeros....

this is one variation of what i've tried to read in the scores and at least print them out individually as integers

while (getline(fin,grades))
{
   getline(fin,grades);
   std::cout << grades;
   std::istringstream str(grades);
   int score;
   while (str>>score)
   {
      int s;
      str >> s;
      std::cout << score<< '\n';
   }

thanks so much for any help

Based on your description of the input file, I think what you have is correct except you don't need the getline again after the while loop, you also seem to be reading score twice on your second while loop, the int score should probably be changed to a double and you should change your couts to ofstream output. Using ofstream is just like using couts, it is like this:

 ofstream out(outputFile); // open the output file 
                            // for output average

out << grades << average(str) << "\n"; // output your stuff to the file in the while loop like this 
out.close(); // closing the file 

Then since you are confused with istringstream, I would use istringstream to read each number and compute the average using another function like this. Here is my istringstream function to compute the average assuming the last thing being read is the total. Another approach would be since the total is already given to you, I would store all the inputs for the line in a vector or an array, and then get the last element divided by the size - 1 which should give you the average.

double average(istringstream& str){ // compute the average based on the line stream  
    double sum = 0; // sum of all the numbers in a line 
    int count = 0; // number of numbers in a line 
    double score; // score that is being read in the line 
    while(str>>score){ // can read a score
      sum += score; // add the scores to a sum 
      count++; // count the number of numbers in the line
    }
    sum = sum - score; // the last thing is the line is the total ? 
    count = count - 1; // assuming the last thing in the line is the total ? 
    return sum/count; 
}

Hope that will provide enough hints to do this. Oh and don't forget to close the input streams and output streams. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM