Converting strings to numbers in C++ makes a lot of people depressed because of their inefficiency and user unfriendliness. See how string 100
can be converted to int
:
#include <sstream> void sample1() { std::istringstream iss("100"); int i; iss >> i; // ... }
It is better not to think, how many unnecessary operations, virtual function calls, atomic operations, and memory allocations occurred during the conversion from earlier. By the way, we do not need the iss
variable any more, but it will be alive until the end of scope.
C methods are not much better:
#include <cstdlib> void sample2() { char * end; const int i = std::strtol ("100", &end, 10); // ... }
Did it convert the whole value to int
or stopped somewhere in the middle? To understand that we must check the content of the end
variable. After that we'll have a useless end
variable getting in the way until the end of scope. And we wanted an int
, but strtol...