使用带有">>"运算符的 std::istringstream 的奇怪行为

Strange behaviour using std::istringstream with '>>' operator

本文关键字:gt istringstream 运算符 std      更新时间:2023-10-16

我注意到下面非常简单的程序有一个奇怪的行为。

#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
    std::string data = "o BoxModelnv 1.0f, 1.0f, 1.0fnv 2.0f, 2.0f, 2.0fn";
    std::istringstream iss(data);
    std::string line;
    std::string type;
    while (std::getline(iss, line, 'n'))
    {
        iss >> type;
        std::cout << type << std::endl;
    }
    getchar();
    return (0);
}

输出如下:

v
v
v

但我想要以下一个:

o
v
v

我尝试了这个解决方案:

#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
    std::string data = "o BoxModelnv 1.0f, 1.0f, 1.0fnv 2.0f, 2.0f, 2.0fn";
    std::istringstream iss(data);
    std::string line;
    std::string type;
    iss >> type;
    std::cout << type << std::endl;
    while (std::getline(iss, line, 'n'))
    {
        iss >> type;
        std::cout << type << std::endl;
    }
    getchar();
    return (0);
}

但输出如下:

o
v
v
v

请问有人可以帮助我吗?提前非常感谢您的帮助。

调用 getline 后,从字符串流的缓冲区中删除第一行。字符串中第一个换行符之后的单词是"v"。

在 while 循环中,使用该行作为输入创建另一个字符串流。现在从这个字符串流中提取你的类型单词。

while (std::getline(iss, line, 'n'))
{
    std::istringstream iss2(line);
    iss2 >> type;
    std::cout << type << std::endl;
}