Find last token in stringstream

860 Views Asked by At

I have a stringstream and must find out if it ends with a certain word or not. How do you iterate over the stringstream and pick out the last string?

It's a school excercise in which you are not allowed to use iterators or any other magic.

1

There are 1 best solutions below

9
On BEST ANSWER

A string stream is kind of like snprintf in C, so you actually convert it to a string via the .str() method. This is a basic example: To actually get all the worlds you will have to split on space, and put it into an array or vector, or something.

#include <iostream>
#include <string>
#include <sstream>
using std::cout;
using std::endl;
int main()
{
        std::stringstream ss;
        ss << "self" << ' ' << "world" << ' ' << "bacon";
        std::string str(ss.str());
        std::string buf;

        for(unsigned i = 0; i < str.length(); i++) {
                buf += str[i];
                if(str[i] == ' ') {
                        buf = "";
                }
        }
        cout << buf << endl;
        return 0;
}