0

I'm new to C++ so I've been having a bit of trouble getting used to and learning how to deal with it. So pretty much, what I'm trying to is write a program that would open a textfile containing 5 lines of text, each with 5 integer numbers separated by spaces, then write to the console each individual integer from each line one at a time followed by a comma and the running average. I've managed to get the console to display the whole line of integers and the running average from the first integer of each line. Any help or advice would be appreciated :)

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;

int main()
{
    string filename;
    string mystring;
    double average = 0;
    double total = 0;
    int i = 1;

    cout << "Enter name of file to open: " << endl;
    cin >> filename;

    ifstream inputfile;
    inputfile.open(filename.c_str());

    if (!inputfile)
    {
    cout << "Error opening file: " << filename << endl;
    return -1;
    }

    while (!inputfile.eof())
    {
    getline(inputfile, mystring);
    total = atof(mystring.c_str()) + total;
    average = total / i;

    cout << mystring << " , " << average << endl;

    i++;
    }

    inputfile.close();
}

1 Answers1

0

Just check Split a string in C++? to see how to split mystring into a std::vector<std::string>, then you can iterate through this vector, that will iterate through all items of one line.

Something like that:

void split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

while (!inputfile.eof())
{
    getline(inputfile, mystring);

    std::vector<std::string> items;
    split( mystring, ' ', items );
    if ( !items.empty() )
    {
        for ( std::vector<std::string>::iterator iter = items.begin(); iter != items.end(); ++iter )
        {
            total = atof(iter->c_str()) + total;
        }
        // not clear why you were dividing by i
        // you may divide by item.size() if you want the average of every items on the line
        average = total / items.size();

        cout << mystring << " , " << average << endl;

    }
}
Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151