You can use string stream in the <sstream>
header.
string myString = "123";
stringstream sStream( myString );
int convertedInt;
sStream >> convertedInt.
题
I've populated a string vector with with numbers and characters (*,+,-,/
). I want to assign each number and character to two new vector, and int
vector and a char
vector. Is there a way to convert the everything from string to the desired data type?
解决方案
You can use string stream in the <sstream>
header.
string myString = "123";
stringstream sStream( myString );
int convertedInt;
sStream >> convertedInt.
其他提示
Include the <sstream>
header and you can do something like this:
std::vector<std::string> stringVector = /* get data from somewhere */
std::vector<int> intVector;
std::vector<char> charVector;
for (std::vector<std::string>::const_iterator it = stringVector.begin(); it != stringVector.end(); it++)
{
if (it->length() == 0)
continue; // ignore any empty strings
int intValue;
std::istingstream ss(*it);
if (ss >> someValue) // try to parse string as integer
intVector.push_back(someValue); // int parsed successfully
else
charVector.pushBack((*it)[0]);
}
This assumes anything that cannot be parsed as an integer should be pushed into the char vector instead (so, 234
, 100000
and -34
will be put into intVector
, and /
, +
etc will be put into charVector
). Only the first character of a non-integer value is pushed, so if you have *hello
or *123
, only *
will be put into the charVector
.
If you are using C++11, you can swap the std::vector<std::string>::const_iterator
with auto
to make it look a bit nicer.