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?
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?
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].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With