Return value of atoi (argv[1]) is always 0
質問
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]
.
atoi
has no way of signalling a conversion error, such as when trying to parse a
. Use strtol
instead, which gives you enough information to determine whether the conversion succeeded:
#include <stdlib.h>
char const * input = "abc"; // this could be argv[i]
char * e;
long int n = strtol(input, &e, 0);
if (*e != '\0') { /* conversion error! */ }
else { /* n is valid */ }