#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if(argc != 2)
return 1;
if(!atoi(argv[1]))
printf("Error.");
else printf("Success.");
return 0;
}
My code works when I enter an argument that is either below or above the value of zero.
[griffin@localhost programming]$ ./testx 1
Success.
[griffin@localhost programming]$ ./testx -1
Success.
[griffin@localhost programming]$ ./testx 0
Error.
Why doesn’t it work?
It’s very simple,
atoireturns the number converted which in your case is exactly0(as expected).There is no standard method of checking whether the conversion actually succeeded or not when using
atoi.Since you are writing c++ you could get the same result with better error checking by using a
std::istringstream,std::stoi(C++11) orstrtol(which is a better interface when dealing with arbitrary numbers).std::istringstream example
std::strtol example
std::stoi (C++11)