C++ - 重复使用istingstream
我有一个代码用于读取在线存储的带有浮点数的文件,如下所示:“3.34|2.3409|1.0001|...|1.1|”。我想使用 istringstream 读取它们,但它无法按我的预期工作:
string row;
string strNum;
istringstream separate; // textovy stream pro konverzi
while ( getline(file,row) ) {
separate.str(row); // = HERE is PROBLEM =
while( getline(separate, strNum, '|') ) { // using delimiter
flNum = strToFl(strNum); // my conversion
insertIntoMatrix(i,j,flNum); // some function
j++;
}
i++;
}
在标记点中,行仅第一次复制到单独的流中。在下一次迭代中它不起作用并且什么也不做。我预计可以使用更多次,而无需在每次迭代中构造新的 istringstream 对象。
I have a code for reading files with float numbers on line stored like this: "3.34|2.3409|1.0001|...|1.1|". I would like to read them using istringstream, but it doesn't work as I would expect:
string row;
string strNum;
istringstream separate; // textovy stream pro konverzi
while ( getline(file,row) ) {
separate.str(row); // = HERE is PROBLEM =
while( getline(separate, strNum, '|') ) { // using delimiter
flNum = strToFl(strNum); // my conversion
insertIntoMatrix(i,j,flNum); // some function
j++;
}
i++;
}
In marked point, row is copied into separate stream only first time. In next iteration it doesn't work and it does nothing. I expected it is possible to be used more times without constructing new istringstream object in every iteration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将行设置到 istringstream...
... 通过调用重置它
这会清除在上一次迭代中或通过设置字符串设置的任何 iostate 标志。
http://www.cplusplus.com/reference/iostream/ios/clear/
After setting the row into the istringstream...
... reset it by calling
This clears any iostate flags that are set in the previous iteration or by setting the string.
http://www.cplusplus.com/reference/iostream/ios/clear/
您需要在
separate.str(row)
之后添加separate.clear();
行来清除状态位,否则eofbit
会得到设置和后续读取失败。You need to add a
separate.clear();
line afterseparate.str(row)
to clear the status bits, otherwise theeofbit
gets set and subsequent reads fail.