#include <iostream> #include <charconv> #include <string.h> // Regular atoi() returns zero when it cannot parse the string. // So you don't know if its "0" or "junk". // This function will return false when it cannot parse the entire string. bool better_atoi(const char *number_as_string, int &iValue) { const char *last = number_as_string + strlen(number_as_string) - 1; auto [ptr, ec] = std::from_chars(number_as_string, last, iValue); return ec != std::errc{} && ptr == last; } int main() { const char *number_as_string = "12.34"; int iValue; const bool result = better_atoi(number_as_string, iValue); std::cout << "success=" << result << "\n"; std::cout << "iValue=" << iValue << "\n"; }
Programming Tips - C++: a more robust atoi() using std::from_chars()
Date: 2023sep25
Language: C++
Q. C++: a more robust atoi() using std::from_chars()
A. // Requires C++2017+