Who can teach me the purpose of stringStream, and how to use it, please.
I have read some paper about this, but I still have something don't understand.

Recommended Answers

All 2 Replies

Who can teach me the purpose of stringStream, and how to use it, please.
I have read some paper about this, but I still have something don't understand.

Stringstream is identical to a file stream, except that there is no file. Instead it stores the information in a string container. This means you can have the benefits of the extraction and insertion operators (and the other stream operators) without having to read and write to a file. In practice, it has little to do with strings, except that the string container is the method by which it stores information, and you can use .str() to retrieve the string.

stringstream ss;
float a = 55.55;
int b = 6;
float c;
float d;
ss << a; //ss converts float to string and now holds the string 55.55;
ss << b; //ss converts int to string now holds the string "55.55 6"
cout << ss.str() //outputs "55.55 6";
ss >> c; //ss converts string to float and c now holds 55.55;
ss >> d; //ss converts string to float and d now holds 6;

These conversions can be messy to implement by hand, so this is the most common use for stringstream.

stringstream is also useful for handling a line at a time out of a file (or other stream):

Untested, so I apologize in advance if it doesn't compile:

ifstream inf ("someFile.txt");
string line;
while (getline(inf, line)) {
    stringstream ins(line);
    string word;
    while (line >> word) {
        // handle each word on the line
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.