Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphanumeric to numeric in c ambiguity

Tags:

c++

c

All,

functions which check and covert if a string is a numerical or not such as atol and atoi ... I checked in c/c++ reference in atol description and it was written like this in the case of absence of any numeric in the string.

no conversion is performed and zero is returned.

Obviously this may be an ambiguity if the string i passed is "0" so atol will returns a zero same as the precedent case.

As the function signature is int atoi() or long atol() the returned value might be an int or long so the returned value will match in all cases with a returned value of a real int.(i mean even though atoi returns a negative value for no-numeric string this returned value matches with the conversion of the string of this value it self) ambiguity persist

is it unsafe to check a string if it is a numeric or not using this functions? what would be the good solution for this case?

like image 514
Aymanadou Avatar asked Jan 20 '26 11:01

Aymanadou


2 Answers

Use strtol or strtoll, they return the position of the first invalid character so you know if any conversion has take place.

like image 166
chill Avatar answered Jan 23 '26 03:01

chill


(int)strtol()

You can pass a char * to verify conversion

like image 36
David Ranieri Avatar answered Jan 23 '26 02:01

David Ranieri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!