I want to process user input as an integer, but it seems as though C has no way to get an int from stdin. Is there a function to do this? How would I go about getting an int
Aside from (f)scanf
, which has been sufficiently discussed by the other answers, there is also atoi
and strtol
, for cases when you already have read input into a string but want to convert it into an int
or long
.
char *line;
scanf("%s", line);
int i = atoi(line); /* Array of chars TO Integer */
long l = strtol(line, NULL, 10); /* STRing (base 10) TO Long */
/* base can be between 2 and 36 inclusive */
strtol
is recommended because it allows you to determine whether a number was successfully read or not (as opposed to atoi
, which has no way to report any error, and will simply return 0 if it given garbage).
char *strs[] = {"not a number", "10 and stuff", "42"};
int i;
for (i = 0; i < sizeof(strs) / sizeof(*strs); i++) {
char *end;
long l = strtol(strs[i], &end, 10);
if (end == line)
printf("wasn't a number\n");
else if (end[0] != '\0')
printf("trailing characters after number %l: %s\n", l, end);
else
printf("happy, exact parse of %l\n", l);
}