0

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.

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by raptr_dflo
0

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.

0

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
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.