Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

argv

atoi

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?

like image 347
Bing Lu Avatar asked Dec 18 '25 00:12

Bing Lu


2 Answers

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?

like image 145
Luchian Grigore Avatar answered Dec 20 '25 18:12

Luchian Grigore


atoi() converts a char string to a number - but only if the string is a number.

If you want to print 'a' as an ASCII value just use %d and argv[1][0], i.e. the first character of string argv[1].

like image 34
Martin Beckett Avatar answered Dec 20 '25 17:12

Martin Beckett



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!