1

I am learning how to program in C++. My program is supposed to read lines that consist of a string value and double values from an input file and then write the strings and the average of the double values of each line to an output file. The strings are id numbers and the quantity of the double values can vary from line to line.

example:

input file:
9875 1, 2, 3, 4

9324 5, 5, 7, 8, 9

7458 9, 10, 11

output file:

9875 2.5

9324 6.8

7458 10

I used a vector to hold the value of the double values and calculated the sum of the values. My issue is that when my program is reading through the input file it does know when a line ends and a new line begins and outputs the average all of the double values and the string values(which are id numbers). How would I go about telling the program when a line ends? Here is my code thus far:

#include <fstream>; 
#include <iostream>;
#include <string>; 
#include <vector>; 

using namespace std; 

int main()
{
    ifstream inFile;
    ofstream outFile;

    string id;             
    double num;
    double sum = 0;
    string line;
    vector<double> avgs; 

    inFile.open("in.txt");
    outFile.open("out.txt");

if (inFile)
{

        inFile >> id >> num;

            //read the values from the input file into the vector  
            while(inFile >> num)
            {
                avgs.push_back(num); 

            }

                for (int n : avgs)
                {
                    sum += n;
                }

                outFile << "     " << id << "          " << avgs.size() << "                  " << (sum / avgs.size()) << endl;

}
else
{
    cout << "Error" << endl;
}
inFile.close();
outFile.close();

return 0;

}

Code.girl
  • 149
  • 2
  • 3
  • 9
  • can you elaborate? I have endl written at the end of my output file operands. – Code.girl Jan 26 '16 at 05:32
  • 1
    Your title suggests you have a problem writing data on a per line basis – Marged Jan 26 '16 at 05:50
  • 1
    Maybe using ifstreams `getline` and this http://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings will help you. – Support Ukraine Jan 26 '16 at 06:00
  • The question asks you to read line by line, but your program doesn't do that. You need to investigate `getline` to read a line at a time and then `istringstream` to read the numbers in the line you have just read. – john Jan 26 '16 at 06:43

0 Answers0