You can't just use sscanf() as a drop-in replacement for scanf(). sscanf() parses its tokens from a char[] array rather than from stdin. So the general idea is that you use fgets() or a similar function to read data into a buffer, and then use sscanf() to parse that buffer. Quick example:
Code:
#include <stdio.h>
int main() {
char buffer[BUFSIZ];
int x, y, z;
printf("Enter exactly three numbers on one line:\n");
for(;;) {
int bogus;
if(!fgets(buffer, sizeof buffer, stdin)) return 1;
if(sscanf(buffer, "%d%d%d%d", &x, &y, &z, &bogus) != 3) {
printf("Hey. I said *exactly* three numbers.\n");
}
else break;
}
printf("Product %d*%d*%d = %d\n", x, y, z, x*y*z);
return 0;
}
Example run:
Code:
Enter exactly three numbers on one line:
1 2
Hey. I said *exactly* three numbers.
1 2 3 4
Hey. I said *exactly* three numbers.
1 2 3
Product 1*2*3 = 6
There are other ways to see if the user entered data beyond what you expected. You could use %p to see how far sscanf() read and then see if there were any non-space characters between there and the end of the string (or just use %c to make your life a lot easier).