0

I've noticed a strange behaviour with the very simple program just below.

#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);
}

The output is the following :

v
v
v

But I want the following one :

o
v
v

I tried this solution :

#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);
}

But the output is the following :

o
v
v
v

Does anyone can help me, please ? Thanks a lot in advance for your help.

user1364743
  • 5,283
  • 6
  • 51
  • 90

1 Answers1

2

After calling getline, you remove the first line from the stringstream's buffer. The word in the string after the first newline is "v".

In your while loop, create another stringstream with the line as input. Now extract from this stringstream your type word.

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

    std::cout << type << std::endl;
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • @user1364743 If it is the answer to your question then please accept it. Here at StackOverflow we don't say thank you, we upvote and/or accept answers. – Ali Oct 01 '13 at 13:50