finput and stringstream (c++)
finput and stringstream (c++)
我们在课堂上学习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。你没有初始化total
和count
的值,所以它们只会增长;声明
int value = 0, total = 0, count = 0;
在从file中读取的循环中
2。你不输出打印值之间的空格;使用
cout << name << " " << total << " " << fixed << setprecision(1) << total * 1.0 / count << endl;
当输出。
相关文章:
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 使用 "stringstream " 将字符串转换为整数
- std::stringstream 返回字符 *
- std::stringstream::flush() 应该做什么吗?
- 静态 std::stringstream 的叮当整警告
- Stringstream编译错误仅发生在linux环境中
- "stringstream"复制构造它的字符串吗?
- 为什么"std::stringstream::stringstream(std::string&&)"不存在?
- 为什么 {fmt} 比 std::stringstream 慢?
- C++命令末尾的 std::stringstream 空格
- 返回 std::stringstream - 编译失败
- C++ std::stringstream 运算符<< vs (构造函数)
- 流从STD :: Stringstream带有空间的流
- 使用C STL StringStream记录具有实时性能要求
- iStream 未完全恢复已放入 Stringstream 的内容
- 使用StringStream将字符串转换为int
- 用std :: stringstream inline代替字符
- 为什么我无法从 std::stringstream 二进制流中获得全精度(双精度、浮点数)
- 调用"stringstream::str()"来获取打印的内容实际上是合法的吗?