通过字符串流更新 int
Updating int through stringstreams
我试图从文件中逐行读取一对值,但整数i
和j
没有更新。我的i
和j
分配错了吗?我已经找到了一种让代码工作的方法,但我很好奇为什么第一个 while 循环不起作用。
控制台输出:
127 86
127 86
141 127
127 86
153 127
127 86
165 127
127 86
171 127
127 86
174 127
127 86
191 27
127 86
191 87
127 86
191 99
127 86
191 102
127 86
女工程师:
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
void test()
{
ifstream inputfile;
inputfile.open("test.txt");
string line;
stringstream lineS;
int i, j;
while ( getline( inputfile, line ) )
{
lineS.str(line);
cout << lineS.str() << endl;
lineS >> i >> j;
cout << i << " " << j << endl << endl;
}
/* This works
while (!inputfile.eof()) {
inputfile >> i >> j;
cout << i << " " << j << endl << endl;
}*/
inputfile.close();
}
int main()
{
test();
return 0;
}
这是文本文件测试.txt:
127 86
141 127
153 127
165 127
171 127
174 127
191 27
191 87
191 99
191 102
问题似乎是,当您从lineS
读取一次时,会设置eofbit
标志,并且在重置字符串时不会清除它。要么是这样,要么是标准库代码中存在错误,当您重置字符串时,该错误无法正确重置读取位置。
两种解决方案:每个循环手动清除流状态,或在循环内定义lineS
。
您尚未重置流的指向字符串开头的 get 指针。更改基础字符串并不重要。
更好的习语是在循环中构造字符串流:
while ( getline( inputfile, line ) )
{
istringstream lineS( line );
lineS >> i >> j >> ws;
if (!lineS.eof()) inputfile.setstate( ios::failbit );
}
另请注意,任何输入错误都会被识别并传播回原始输入流。
希望这有帮助。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 从C++本机插件更新Vector3数组
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何更新最近在 std::vector<pair<int, int>> 中输入的元素?
- 如何在不复制的情况下更新 std::unordered_map<std::string, std::vector> 中的向量<int>?
- 如何更新游戏中的INT转换
- 无法在 while 循环之外更新 int
- 通过字符串流更新 int
- Directx9 字体更新,从 int 转换为 LPCTSTR
- 在类型上使用运算符 [][] 时,不会更新值:map<int、map<int、int> >