Return value of atoi (argv[1]) is always 0

Bing Lu picture Bing Lu · Oct 14, 2012 · Viewed 17.9k times · Source

I'm running into a problem about return value of atoi().

I want to convert the char in command line argument argv[1] into int type and print it out.

Here is my code.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i;
    //print the char in *argv[]
    for(i = 0; i < argc; i++)
    {
            fprintf(stdout, "Arg %d: %s\n", i, argv[i]);
    }

    if (argc > 1)
    {
        i = atoi(argv[1]);      //convert char to int
        fprintf(stdout, "Int version of 1st arg: %d\n", i);
    }

    return 0;
}

I compile it by gcc and run it like ./a.out a b c

Other result is correct, but the atoi() result always displays as

Int version of 1st arg: 0

Could you give me some suggestion on this topic?

Answer

Luchian Grigore picture Luchian Grigore · Oct 14, 2012

My suggestion is that if you want to convert a string to an int, provide as parameter a string that can actually be converted to an int. Your arguments are:

 ./a.out a b c

so no ints. What did you expect? What do you think a converted to an int is?