使用带有'>>'的std :: istringstream的奇怪行为操作者

时间:2013-10-01 12:38:31

标签: c++ istringstream

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

#include <iostream>
#include <sstream>
#include <string>

int main(void)
{
    std::string data = "o BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n";
    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 BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n";
    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

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

1 个答案:

答案 0 :(得分:2)

调用getline后,从stringstream的缓冲区中删除第一行。第一个换行符后面的字符串中的单词是“v”。

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

while (std::getline(iss, line, '\n'))
{
    std::istringstream iss2(line);
    iss2 >> type;

    std::cout << type << std::endl;
}