I guess I would use the C++ way of doing it with stringstream Though people prefer using atoi() which is not a standard and which is basically the "C" way of doing it :)
#include <sstream> //required for conversion.
using namespace std;
string str="1991"; //Contains a string.
stringstream convert; //Make a stringstream.
convert<<str; // Put the value of str into the string stream.
convert>>num; // Get the value back into a integer.
>Though people prefer using atoi() which is not a standard and which is basically
>the "C" way of doing it atoi is as standard as the stringstream solution. The only problem is that it is not that 'good'.
By good means that as the stringstream solution will rely on the standard iostream library, it will tend to be more robust.
One have plenty of good reasons to choose iostream rather than the C cstdio which are listed here.
The stringstream is elegant albeit slow. But as the rules says: `` Don't care about small optimization until you profile your code"
My final advice : use string stream in general and use atoi if speed is an issue.
use string stream in general and use atoi if speed is an issue.
That's close to my advice. But I say use strtol because atoi doesn't have any error handling capability. Boost:lexical_cast and Boost::numeric_cast are even simpler than ad hoc string stream code or robust strtol code, but you have to have Boost to use them.