_wtoi return zero: input or non-digital input?

_ wtoi , when it is not possible to convert the input, so the input is not an integer, returns zero. But at the same time, the input may be zero. Is this a way to determine if the input was incorrect or zero?

+4
source share
1 answer

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) { //error } 

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) { //error } 
+4
source

Source: https://habr.com/ru/post/1413561/


All Articles