简体   繁体   中英

Converting std::string to integer

ALL, Here is my code:

std::string version = curl_version();
version = version.substr( version.find( '/' ) + 1 );
int min, max;
int pos = version.find( '.' );
std::stringstream stream( version.substr( 0, pos ) );
version = version.substr( pos + 1 );
stream >> max;
pos = version.find( '.' );
stream.str( version.substr( 0, pos ) );
stream >> min;

I'm just reusing the same stream object but for some reason min variable is not assigned properly.

What am I missing?

Thank you.

The problem is that you can't reuse the same stringstream object, try doing like this instead:

std::string version = curl_version();
version = version.substr( version.find( '/' ) + 1 );
int min, max;
int pos = version.find( '.' );
std::stringstream stream( version.substr( 0, pos ) );
version = version.substr( pos + 1 );
stream >> max;
pos = version.find( '.' );
std::stringstream stream1( version.substr( 0, pos ) );
stream1 >> min;

It seems that when you shift (>>) out of a stringstream and it reaches eof (you can check by calling stream.eof()) a flag is set that prevents further shifting out even if you set (by calling str()) a new associated string object. To make it work, you have to call clear() before shifting out again.

std::string version = curl_version();
version = version.substr( version.find( '/' ) + 1 );
int min, max;
int pos = version.find( '.' );
std::stringstream stream( version.substr( 0, pos ) );
version = version.substr( pos + 1 );
stream >> max;
pos = version.find( '.' );
stream.str( version.substr( 0, pos ) );
str.clear();
stream >> min;

The reason is, that just calling std::stringstream::str does change the internal string, but it doesn't reset any error flags. So when the previous string reached the end of the string or another "error", the stream still thinks it's at this error. Just call std::striungstream::clear to clear the error flags after changing the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM