istream::operator>>(int&) 似乎对空格的行为很奇怪

istream::operator>>(int&) seems to behave weirdly with whitespaces

本文关键字:gt 空格 operator int istream      更新时间:2023-10-16

出于某种原因,运算符>>在我的程序中表现得很奇怪。

这是代码:

ifstream fs;
fs.open(filename, ifstream::in);
if (!fs)
{
cout << "File could not be read" << endl;
return;
}
string input;
map<int, pair<Vec3, int> > skeleton;
while (getline(fs, input))
{
stringstream ss(input);
cout << "stream " << ss.rdbuf() << endl;
int nodeId(-1);
ss >> nodeId;
cout << "stream " << ss.rdbuf() << endl;
cout << "nodeId " << nodeId << endl; \program stops before outputting "nodeId"
Vec3 nodePosition(1);
ss >> nodePosition;
cout << "stream " << ss.rdbuf() << endl;
int prevId(0);
ss >> prevId;
cout << "stream " << ss.rdbuf() << endl;
skeleton[nodeId] = pair<Vec3, int>(nodePosition, prevId);
cout << ss.rdbuf() << endl;
}

我的文件如下所示:

0 -0.0647035 54.1029 0.645867 -1
1 4.25456 48.2454 1.73375 0
2 5.94451 27.2658 -0.00329354 1
3 6.5392 4.91011 -2.80206 2
...
  • 每行int float float float int,用空格分隔,行尾一n

想法:我想将该文件读入映射,每行分别读取,所以我使用getline读取一行,然后将该行放入字符串流中。我现在想读取 5 个数字中的每一个,将第一个保存在 int 中,接下来的三个保存在一个Vec3中(这只是 3D 空间中的向量,对于哪个运算符>>正确重载(,最后一个再次保存在 int 中,所以我使用ss >> nodeIdss >> nodePositionss >> prevId.

问题:程序在指示的行停止。它不会崩溃或给出任何异常,它只是停止。这是输出:

stream 0 -0.0647035 54.1029 0.645867 -1
stream

之后它只是停止并且什么也不做。查看调试器(我将断点放在带有注释的行中(,流似乎是空的(_Chcount0(,而且它似乎也没有将任何内容写入nodeId,因为这仍然是-1

预期行为:getline末尾从文件中读取一行(不带n(。每次调用istream::operator >> (int&)提取字符,直到到达空格(与所有其他类似的流运算符一样(,将提取的字符解释为数字并将其保存到nodeId中。

我知道我可以将find_first_ofinput一起使用并将其转换为数字,但我想知道我在这里哪里出错了。

提前感谢!

您无法从字符串流中读取,因为日志会弄乱 ss 缓冲区。cout << ss.rdbuf();读取 ss,直到结束,并将其位置移动到缓冲区的末尾。

只需删除代码中cout << ss.rdbuf日志,它就会按预期工作。

无论如何,如果您想使用rdbuf,您可以这样做:

stringstream ss(somestring);
int pos = ss.tellg(); //store the position
cout << ss.rdbuf() << endl;
ss.seekg(pos); //restore position

根据Igor Tandetnik的评论编辑。

您可以尝试以下代码

fs.open(filename, ifstream::in);
if (!fs)
{
cout << "File could not be read" << endl;
return;
}
string input;
map<int, pair<Vec3, int> > skeleton;
while (getline(fs, input))
{
stringstream ss(input);
int nodeId(-1);
ss >> nodeId;
cout << "nodeId " << nodeId << endl;
Vec3 nodePosition(1);
ss >> nodePosition;
int prevId(0);
ss >> prevId;
skeleton[nodeId] = pair<Vec3, int>(nodePosition, prevId);
}

不使用 RDBUF(( 函数打印字符串流内容