istream :: operator>>(int&)似乎与空格

时间:2017-07-13 13:21:19

标签: c++ stl

由于某种原因运营商>>在我的程序中表现得非常奇怪。

这是代码:

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空间中的向量,运算符&gt;&gt;正确重载)和最后一个再次使用int,我使用ss >> nodeIdss >> nodePositionss >> prevId

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

stream 0 -0.0647035 54.1029 0.645867 -1
stream

之后它就会停止并且什么都不做。查看调试器(我将断点放在注释的行),流似乎是空的(_Chcount0),它似乎没有写入任何内容{{1或者,因为那仍然是nodeId

预期行为:-1从文件中读取一行(不包含getline)。每次\n调用都会提取字符,直到它到达空格(与所有其他类似的流操作符一样),将提取的字符解释为数字并将其保存到istream::operator >> (int&)

我知道我可以nodeId使用find_first_of并将其转换为数字,但我想知道我在哪里出错。

提前致谢!

2 个答案:

答案 0 :(得分:1)

你无法从stringstream读取,因为你的日志混淆了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评论编辑。

答案 1 :(得分:1)

您可以尝试以下代码

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()函数打印stringstream内容