The code below runs but it doesn't print the 8 at all.
The number one thing to learn here is to enable all compiler warnings. This saves you (and us) time.
A good, well enabled compiler with report something like
UserInput1 = argv[1];
// warning: assignment to 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
printf("%s\n", UserInput1);
// warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]
Code is attempting to change a pointer to an int
. Instead, use a function to read the string pointed to by argv[1]
as decimal text and convert to an integer.
read a command line argument ... and to be able to access
argv[1]
deserves some tests. Not all strings represent an integer.
Does it exist?
Is there a string to parse?
if (argc < 2) {
puts("argv[1] missing");
}
Convert from a string to an integer
Do we want to limit the range? Is "123456789012345678901234567890" OK?
Let us assume the int
range.
C, sadly, does not have a robust conversion function to int
, but does them for wider types.
errno = 0;
char *endptr;
long number = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Outside long range");
} else if (number < INT_MIN || number > INT_MAX) {
errno = ERANGE;
puts("Outside int range");
} else if (*endptr)) {
puts("Extra text after the number");
} else {
int UserInput1 = (int) number;
printf("Success %d\n", UserInput1);
}