使用字符串流从 c++ 中的字符串中提取整数时意外重复
Unexpected repetition while extracting integers from string in c++ using stringstream
我正在尝试读取一个由空格分隔的整数组成的行组成的文件。我想将每行存储为单独的整数向量。所以我尝试逐行读取输入并从中提取整数
stringstream
我用于提取的代码如下 -
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("input.txt","r",stdin);
string line;
while(getline(cin, line)) {
int temp;
stringstream line_stream(line); // conversion of string to integer.
while(line_stream) {
line_stream >> temp;
cout << temp<< " ";
}
cout << endl;
}
return 0;
}
上面的代码有效,但它重复最后一个元素。例如,输入文件 -
1 2 34
5 66
输出:
1 2 34 34
5 66 66
我该如何解决这个问题?
因为这个:
while(line_stream) {
line_stream >> temp;
cout << temp<< " ";
}
失败的原因与while (!line_stream.eof())
失败的原因相同。
当您读取最后一个整数时,您还没有到达流的末尾 - 这将在下一次读取时发生。
下一次读取是未选中的line_stream >> temp;
,它将失败并保持不变temp
。
这种循环的正确形式是
while (line_stream >> temp)
{
cout << temp<< " ";
}
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 如何从C++中的格式化字符串派生整数?
- 如何使用C++将字符串中的字符转换为整数变量
- 向量值(字符串和整数)求和C++
- 如何从字符串C++读取多个整数
- 如何将整数字符串转换为整数的二维向量?
- 输入验证以筛选出字符、字符串和一系列整数
- 有没有办法在C++中将字符串和整数相乘?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++字符串大小减去整数不是预期值,为什么?
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- C++ runtime_exception字符串 + 整数
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- 使用next_permutation函数后如何保存字符串/整数
- 使用fstream和sstream一起从文件中分离字符串/整数