For a task I need use if atoi(INPUT) == 0 to check that a users input is a valid integer and not 0. The problem is when I enter any string that starts with an integer, it is automatically accepted, even if there are non-integer characters after the integer, for example "1aaaabcc" is accepted.
I understand that atoi() is in the example I just stated, would take the 1 and ignore it, but theortically this should be wrong input from the user since it is not a valid integer. Would there be something to add to my code (without adding any libraries) or change something with atoi to fix this?
Please let me know if you need sample code in case its not clear.
The function
atoiis an "alias" for this function callSo in your case you should use the function
strtoland pass the second argument unequal toNULLthat points to a pointer. In this case you can check whether the pointer points to the end of the corresponding string.Here is a demonstration program
Its output is
As you can see only in the third call of the function
strtolthe pointerendptrpoints to the terminating zero character'\0'. In all preceding calls it points to the letter'A'that has the ASCII code65.You can also accept or deny strings like for example
"10 ". If to accept such a string then in this case you need to check that the tail of the string contains only white space characters.You should attentively read the description of the function
strtol.