How to accept 3 arguments as int
For example:
console> please enter 3 digits: 1 2 3
I only know how to accept 1 digit using scanf
:
开发者_StackOverflow社区scanf("%d", &space);
You can read in multiple numbers with scanf
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
Have you tried:
scanf("%d %d %d", &num1, &num2, &num3);
That will work fine if you know you want just the three. If you want a variable number, you'll need to do it in a loop, something like:
#include <stdio.h>
int main (void) {
int i, ch, rc, val, count;
// Loop until we get a valid number.
rc = 0;
while (rc != 1) {
printf ("Enter count: "); fflush (stdout);
rc = scanf(" %d", &count);
// Suck up all characters to line end if bad conversion.
if (rc != 1) while ((ch = getchar()) != '\n');
}
// Do once for each number.
for (i = 1; i <= count; i++) {
rc = 0;
while (rc != 1) {
printf ("\nEnter #% 2d: ", i); fflush (stdout);
rc = scanf(" %d", &val);
if (rc != 1) while ((ch = getchar()) != '\n');
}
printf ("You entered %d\n", val);
}
return 0;
}
Running this gives you:
Enter count: 5
Enter # 1: 10
You entered 10
Enter # 2: 20
You entered 20
Enter # 3: 30
You entered 30
Enter # 4: 40
You entered 40
Enter # 5: 99
You entered 99
精彩评论