Assume that i have two types of query one is 1 2 3 and the other one is 2 3
if the head (index 0) is 1, then the total number within the input are 3 (1 2 3)
and if the head is 2 then the total number within the input are 2 number (2 9)
How do I detect it? Thank you
The problem that I have is that I scan the 3 of them
scanf("%d %d %d",&a,&b&c)
so, when I only have total of 2 number in the input (2 3)
The program wont continue
Thank you
CodePudding user response:
You use the return value of scanf()
to detect this, and you should generally always check return values. They are given for a purpose.
#include <stdio.h>
int main(void) {
int a;
int b;
int c;
printf("Please enter 2 or 3 numbers: ");
int n = scanf("%d%d%d", &a, &b, &c);
switch (n) {
case 2:
printf("You have entered 2 numbers, %d and %d\n", a, b);
break;
case 3:
printf("You have entered 3 numbers, %d, %d and %d\n", a, b, c);
break;
default:
printf("Well, you made an error.\n");
break;
}
}
Note 1: Even printf()
returns a value, commonly the number of characters printed. In this simple example, we can ignore it.
Note 2: It is always a very good idea to read the documentation of functions you use, if you don't know them in detail.