-1

We're learning about stringstream and finput in class and I am confused about the values I am getting for this code:

Source Code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>



using namespace std;


main() {

    ifstream finput("input.txt"); // Read File
    string line, name; // Declare variable line and name
    int value = 0, total = 0, count = 0; // Declare variable value, total, and count

    while (!finput.eof()) { // While the end of file has not been reached

        getline(finput, line ); // Get the entire first line of the file and set it to line variable
        istringstream istr(line); // Convert to parsed string
        istr >> name; // first line of str is converted to the name

        while (istr >> value) { // while there are remaining integer values to output

            total += value; // Add value to total
            count++; // add 1 to count

        }

        cout << name << " " << total << fixed << setprecision(1) << total * 1.0 / count << endl;

    }


}

And here is my input file:

Thomas 1
Jack 1 3
Jim 1 2 3

And here is my output:

Thomas 11.0
Jack 51.7
Jim 111.8
Jim 111.8

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

Why am I not getting "Thomas 1", "Jack 2", and "Jim 2"? And why is Jim displaying twice? My professor did not explain very well what exactly stringstream did and how it works.

I would really appreciate the help. Thanks!

Thomas Walker
  • 145
  • 1
  • 7
  • 1
    Note regarding `while (!finput.eof())`: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Oct 06 '16 at 20:07
  • You never reset `total` and `count`. You should also have a space in the output between total and the division of it. – NathanOliver Oct 06 '16 at 20:08

1 Answers1

0

1. You don't initialize the values of total and count so they only grow; declare

int value = 0, total = 0, count = 0;

inside the loop that reads from file.

2. You don't output space between the printed values; use

cout << name << " " << total << " " << fixed << setprecision(1) << total * 1.0 / count << endl;

when outputting.

Uriel
  • 13,905
  • 4
  • 21
  • 43