Sign in to follow this  
Asheh

end of a stingstream?

Recommended Posts

Asheh    354
Im trying to write a small program which takes a series of numbers... "1 2 3 4 5" I want to then extract those numbers into an std::list... So far I have managed to do it, the numbers are all stored in a list and it works correctly. But my problem is that I have to terminate the string with -1 to tell that im at the end of the stringstream. Is there a way to tell that im reading the last number from the stream? Regards Ashley

Share this post


Link to post
Share on other sites
Fruny    1658
After an operation that reads multiple characters (such as integer formatted input), if the end of the stream has been reached, the eof bit is set. You can test it with the eof() member function.

After an operation that reads one character at a time (such as get()), the eof bit is set if you've tried to read past the end. The read operation returns garbage.

In essence, multi-character input functions discard the post-eof garbage, leaving you with clean data as well as setting the flag.

Quote:
I want to then extract those numbers into an std::list...


Sounds like a job for a stream iterator:

#include <list>
#include <string>
#include <sstream>
#include <iterator>

std::string input = "1 2 3 4 5";
std::istringstream iss(input);

std::istream_iterator<int> begin(iss);
std::istream_iterator<int> end;

std::list<int> l(begin, end); // or l.assign(begin,end) if the list already exists.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this