Here is my code to repeatedly read three variables separated by whitespace from user. The format of input should be 'char int int'(e.g b 3 3 ). I use the return value of scanf function to ensure input is exactly three variables.
#include <stdio.h>
int main(void){
int x, y, nargs;
char command;
while(1){
nargs = scanf("%c %d %d", &command, &x, &y);
printf("%d\n",nargs);
if(nargs != 3){
printf("error\n");
break;
}
}
return 0;
}
Input and Output:
g 4 4
3
b 3 3
1
error
The first line input is no problem. But when I input second line, it shows scanf() only read one variable from this line. What's the problem of my code?
" %c%d%d"
is the quick answer. Usingfgets()
and thensscanf(buf, " %c%d%d",...
is better. GTG – chux - Reinstate Monica