-
Trouble with scanf
Hey all,
I'm quite new to coding in general so go easy on me.
I'm trying to replicate a game where entering numbers will perform different actions, where the first number will indicated what kind of action and following numbers will indicate to what extent.
E.g entering "1 2 3 4" would mean go up (1) 2(2) spaces and right(3) 4(4) spaces.
So far I have been able to perform an action when the user inputs 2 different numbers e.g "1 and 2". However, I'm am also required to be able to accept 4 numbers at once by a user e.g "3 3 3 3".
I have tried changing my scanf("%d %d", &a, &b) to 4 %d's however this then requires me to enter 2 more numbers and subsequently my code doesn't work. This is also looped, so the user can perform different actions again and again.
To reiterate, if I enter 2 integers it should perform a certain if statement I wrote. If I enter 3 integers a different action. And likewise for 4 numbers in one input. The user is not asked how many numbers they would like to input either.
Any help would be appreciated.
As a note, I've only learned if and else statements and loops, as well as printf and scanf and functions.
Thanks all!
-
We usually handle this kind of thing by first reading the entire line as a string, and then using sscanf to "scan" the numbers from the string. All the scanf functions return a count of the number of fields that they filled.
Code:
#include <stdio.h>
int main()
{
char line[200];
while (fgets(line, sizeof line, stdin) != NULL)
{
int d1, n1, d2, n2;
int nfields = sscanf(line, "%d%d%d%d", &d1, &n1, &d2, &n2);
if (nfields == 2)
{
printf("==> %d %d\n", d1, n1);
}
else if (nfields == 4)
{
printf("==> %d %d %d %d\n", d1, n1, d2, n2);
}
else
{
printf("Only enter 2 or 4 numbers.\nTry again.\n");
}
}
return 0;
}
This allows lines like "1 2 3 4 5 6" where it will only read the first 4 numbers and ignore the rest.
Also like "1 2 hello 3 4" where it will read only the first 2 numbers and ignore the rest of the line.
If detecting bad input like that is important than you need to do a little more.
-
Is this right?
Quote:
Code:
int nfields = sscanf(line, "%d%d%d%d", &d1, &n1, &d2, &n2);
Maybe:
Code:
int nfields = sscanf(line, "%d %d %d %d", &d1, &n1, &d2, &n2);
-
Quote:
Originally Posted by
flp1969
Is this right?
The format specs that read ints and floats and the format spec "%s" all skip initial whitespace so there's no difference in functionality.
Maybe your version is more readable, though.