0

I get confused with the "istream& getline (istream& is, string& str)"function, and according to http://www.cplusplus.com/reference/string/string/getline/, the following program:

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream s("this is a test");
    std::string line = "line ";
    getline( s, line );
    std::cout << line << std::endl;
    s.str("test again");
    getline( s, line );
    std::cout << s.str() << std::endl;
    std::cout << line << std::endl;

    return 0;
}

I expect the output to be:

line this is a test

test again

test again

but when I test it on Visual Studio, the output is :

this is a test

test again

this is a test

Could anyone explain the frustrating function for me ?

user7116
  • 63,008
  • 17
  • 141
  • 172
JavaBeta
  • 510
  • 7
  • 16

2 Answers2

4

Clear the error flags between the calls to getline:

int main()
{
    std::istringstream s("this is a test");
    std::string line = "line ";
    getline( s, line );
    std::cout << line << std::endl;
    s.str("test again");
    s.clear()   // <<<--------------- to clear error flags
    getline( s, line );
    std::cout << s.str() << std::endl;
    std::cout << line << std::endl;

    return 0;
}

The first getline sets eofbit on the stream. The second one then fails and line stays intact.

With the fix, you'll get:

this is a test
test again
test again

because getline doesn't add to the string, it replaces the content.

jrok
  • 54,456
  • 9
  • 109
  • 141
0

Whatever value line has prior to the call will not matter, as from the documentation for std::getline:

  1. Calls str.erase()

Your second logical error is due to reusing a stream once you've reached its end.

user7116
  • 63,008
  • 17
  • 141
  • 172