Ravi Nankani
Ravi Nankani

Reputation: 599

end of line in stringstream

Let us say we have a file like:

1 2
3 4 5
6 7 8

usually we would do a getline(), and then use string stream to parse inside the line. However the getline returns a string for which we create a stringstream. Is it possible to get the entire contents of file in a string stream and then parse the tokens, also knowing where the end of line lies ?

Upvotes: 1

Views: 1755

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153820

It seems there is not much point in getting the entire file into std::string just to put it into a std::istringstream and read it: you could read from the std::ifstream directly instead. If you really want to get a file into a std::string, here are a few variations:

std::string s0{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
std::string s1( (std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>() );
std::ostringstream out; out << in.rdbuf(); std::string s2 = out.str();

Obviously, you would just use one of these approaches as each one will consume the input stream in. Once you have the file in a std::string you can construct an std::istringstream from it.

I think you can also use

std::stringstream stream;
stream << in.rdbuf();
stream.seekg(std::ios_base::beg, 0);

avoiding the need to read the content into a std::string first.

Upvotes: 1

Related Questions