user1873947
user1873947

Reputation: 1821

Very strange stringstream and std::getline behaviour

I'm fightning with a map loading bug in my engine, and finally I found it. However, it seems it's something wrong with stringstream and getline... Minimal code:

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

int main(int argc, char **argv)
{
    std::string text = "1!2!6|6|5|";
    std::stringstream buffer;
    buffer << text; // insert to buffer

    std::string temp;
    buffer >> temp; // extract
    buffer << temp; // then insert again (i need it in my code to count characters)
    // and I can't count it before, as in my code the buffer is filled from file

    std::string loaded;
    std::getline(buffer, loaded, '!'); //should instert "1" to loaded
    std::cout << loaded; //and it displays nothing, debugger shows loaded is empty
}

Am I doing something wrong or is it a bug? I'm using g++ 4.7 c++11.

Upvotes: 1

Views: 1146

Answers (1)

sampson-chen
sampson-chen

Reputation: 47367

For extracting the string from stringstream in this case, you probably want:

temp = buffer.str();

instead of:

buffer >> temp;

See: extracting formatted (interpreted) data vs. stringstream.str()

Upvotes: 4

Related Questions