Convert a string to a int (C++)


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 1) > Convert a string to a int (C++)

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;
}


/*
 * Program output:
 The string value is 12 and the int value is 12
 Number conversion failed on ZZZ
 *
 */

Script provided by SmartCGIs