0
votes

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.

1
Seems you're trying to do your while (:Rubens

1 Answers

2
votes

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