【问题标题】:Strange behaviour using std::istringstream with '>>' operator使用带有 '>>' 运算符的 std::istringstream 的奇怪行为
【发布时间】:2013-10-01 12:38:30
【问题描述】:

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

#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

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

【问题讨论】:

  • 看来你在尝试你的while (:

标签: c++ istringstream


【解决方案1】:

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

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

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

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

【讨论】:

  • 非常感谢您的回答。再见。
  • @user1364743 如果这是您问题的答案,请接受。在 StackOverflow,我们不会说谢谢,我们支持和/或接受答案。
猜你喜欢
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 2011-11-13
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多