This is C ++, you should use stringstream
to convert:
#include <iostream> #include <sstream> int main() { using namespace std; string s = "1234"; stringstream ss; ss << s; int i; ss >> i; if (ss.fail( )) { throw someWeirdException; } cout << i << endl; return 0; }
A simpler and simpler solution exists with boost lexical_cast
:
#include <boost/lexcal_cast.hpp> // ... std::string s = "1234"; int i = boost::lexical_cast<int>(s);
If you insist on using C, sscanf
can do it cleanly.
const char *s = "1234"; int i = -1; if(sscanf(s, "%d", &i) == EOF) {
You can also use strtol
with a caution, which requires a little thought. Yes, it will return zero for both lines evaluating zero and for error, but it also has the (optional) parameter endptr
, which will point to the next character after the converted number:
const char *s = "1234"; const char *endPtr; int i = strtol(s, &endPtr, 10); if (*endPtr != NULL) {
source share