istream::operator>>(int&) 似乎对空格的行为很奇怪
istream::operator>>(int&) seems to behave weirdly with whitespaces
出于某种原因,运算符>>在我的程序中表现得很奇怪。
这是代码:
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 >> nodeId
、ss >> nodePosition
和ss >> prevId
.
问题:程序在指示的行停止。它不会崩溃或给出任何异常,它只是停止。这是输出:
stream 0 -0.0647035 54.1029 0.645867 -1
stream
之后它只是停止并且什么也不做。查看调试器(我将断点放在带有注释的行中(,流似乎是空的(_Chcount
0
(,而且它似乎也没有将任何内容写入nodeId
,因为这仍然是-1
。
预期行为:getline
末尾从文件中读取一行(不带n
(。每次调用istream::operator >> (int&)
提取字符,直到到达空格(与所有其他类似的流运算符一样(,将提取的字符解释为数字并将其保存到nodeId
中。
我知道我可以将find_first_of
与input
一起使用并将其转换为数字,但我想知道我在这里哪里出错了。
提前感谢!
您无法从字符串流中读取,因为日志会弄乱 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(( 函数打印字符串流内容
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- EASTL矢量<向量<int>>连续的
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- C++为一串单词添加空格
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 如何打印不带空格的输入整数?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?