the
atoi and
char[] constructs are very 'C'-like. char[] is in danger of overflowing, and atoi is an unreliable function, since it returns zero on an error. Which is very unhelpful if the string you're converting is a valid number which represents zero.
The preferred C++ way to convert from string to int uses
stringstream objects instead
CODE
#include <string>
#include <sstream>
#include <iostream>
int main()
{
using namespace std;
string input;
cout << "Enter your age: ";
getline( cin, input );
int age;
stringstream ss(input);
if( ss >> age )
cout << "You are " << age << " years old" << endl;
else
cout << "Invalid input" << endl;
}
stringstream objects are basically memory buffers which hold string data. They're powerful, yet very easy to use (The syntax works the same as cin and cout). The
if test checks to see whether the buffer is in a good state. The buffer will be set to a 'bad' state if its unable to convert from string to int (So you can tell whether the data stored by your int will be valid).