This item was added on: 2003/03/06
The following code shows one method for converting a C++ string to an int. It attempts to ensure the conversion worked successful, and will return true or false accordingly.
#include <sstream>
#include <string>
using namespace std;
bool StringToInt(const string &s, int &i);
int main(void)
{
string s1 = "12";
string s2 = "ZZZ";
int result;
if (StringToInt(s1, result))
{
cout << "The string value is " << s1
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed" <<endl;
}
if (StringToInt(s2, result))
{
cout << "The string value is " << s2
<< " and the int value is " << result << endl;
}
else
{
cout << "Number conversion failed on " <<s2 <<endl;
}
return(0);
}
bool StringToInt(const string &s, int &i)
{
istringstream myStream(s);
if (myStream>>i)
return true;
else
return false;
}