Search code examples
c++g++zeroatoi

Use of atoi when string represents zero?


#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?


Solution

  • It's very simple, atoi returns the number converted which in your case is exactly 0 (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) or strtol (which is a better interface when dealing with arbitrary numbers).


    std::istringstream example

    #include <sstream>
    
      ...
    
    std::istringstream iss (argv[1]);
    int res;
    
    if (!(iss >> res))
      std::cerr << "error";
    

    std::strtol example

    #include <cstdlib>
    #include <cstring>
    
      ...
    
    char * end_ptr;
    
    std::strtol (argv[1], &end_ptr, 10);
    
    if ((end_ptr - argv[1]) != std::strlen (argv[1]))
      std::cerr << "error";
    

    std::stoi (C++11)

    #include <string>
    
      ...
    
    int res;
    
    try {
      res = std::stoi (argv[1]);
    
    } catch (std::exception& e) {
      std::cerr << "error";
    }