snippetcppCritical
How to parse a string to an int in C++?
Viewed 0 times
stringhowparseint
Problem
What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).
Solution
In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.
It will throw an exception on conversion error.
Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: http://en.cppreference.com/w/cpp/string/basic_string/stol
int myNr = std::stoi(myString);It will throw an exception on conversion error.
Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: http://en.cppreference.com/w/cpp/string/basic_string/stol
Code Snippets
int myNr = std::stoi(myString);Context
Stack Overflow Q#194465, score: 186
Revisions (0)
No revisions yet.