I have been searching for a few hours and can't seem to find the answer I'm after. My apologies if this ends up being a duplicate.
Now my program asks the user for 2 integers. Example
Prompt: 15 24
I after going threw other questions so people have mentioned scanf
and fgets
. But each of those were for entering one number at a time, whereas I want both from the one input.
My other issue is error checking. Whether they actually entered an integer or something invalid. Example:
Prompt: Hello World
Prompt: foo 5
Prompt: 4 bar
Prompt: foo
Prompt:
Code:
int get_input(int* x, int* y) {
char* p, buf[LINE_MAX];
int n1, n2;
printf("Prompt: ");
fgets(buf, sizeof(buf), stdin);
n1 = strtol(buf, &p, 10);
if (p == buf || *p != '\n') {
return 0;
}
n2 = strtol(buf, &p, 10);
if (p == buf || *p != '\n') {
return 0;
}
*x = n1;
*y = n2;
return 1;
}
int main(int argc, char** argv) {
int x, y;
if (get_input(&x, &y)) {
printf("Worked: %d %d\n", x, t);
} else {
printf("Invalid\n");
}
return 0;
}
Some of the error checking is missing, but just really stuck on getting the second value if there is one. Also checking if there are more than 2 values. Much help would be appreciated.
References that got me this far: