finput and stringstream (c++)

finput and stringstream (c++)

本文关键字:c++ stringstream and finput      更新时间:2023-10-16

我们在课堂上学习stringstream和finput,我对这段代码得到的值感到困惑:

源代码:

#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;
    }

}

这是我的输入文件:

Thomas 1
Jack 1 3
Jim 1 2 3

下面是我的输出:

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.

为什么我没有得到"托马斯1"、"杰克2"answers"吉姆2"?为什么吉姆展示了两次?我的教授并没有很好地解释stringstream到底做了什么以及它是如何工作的。

我真的很感激你的帮助。谢谢!

1。你没有初始化totalcount的值,所以它们只会增长;声明

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

在从file中读取的循环中

2。你不输出打印值之间的空格;使用

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