问题
I am taking multiple integer inputs using scanf and saving it in an array
while(scanf("%d",&array[i++])==1);
The input integers are separated by white spaces for example:
12 345 132 123
I read this solution in another post.
But the problem is the while loop is not terminating.
What's the problem with this statement?
回答1:
OP is using the Enter or '\n'
to indicate the end of input and spaces as number delimiters. scanf("%d",...
does not distinguish between these white-spaces. In OP's while()
loop, scanf()
consumes the '\n'
waiting for additional input.
Instead, read a line with fgets()
and then use sscanf()
, strtol()
, etc. to process it. (strtol()
is best, but OP is using scanf()
family)
char buf[100];
if (fgets(buf, sizeof buf, stdin) != NULL) {
char *p = buf;
int n;
while (sscanf(p, "%d %n", &array[i], &n) == 1) {
; // do something with array[i]
i++; // Increment after success @BLUEPIXY
p += n;
}
if (*p != '\0') HandleLeftOverNonNumericInput();
}
回答2:
//Better do it in this way
int main()
{
int number,array[20],i=0;
scanf("%d",&number);//Number of scanfs
while(i<number)
scanf("%d",&array[i++]);
return 0;
}
回答3:
You should try to write your statement like this:
while ( ( scanf("%d",&array[i++] ) != -1 ) && ( i < n ) ) { ... }
Please note the boundary check.
As people keep saying, scanf is not your friend when parsing real input from normal humans. There are many pitfalls in its handling of error cases.
See also:
- Using the scanf function in while loop
- Using scanf in a while loop
回答4:
There is nothing wrong with your code as it stands. And as long as the number of integers entered does not exceed the size of array, the program runs until EOF is entered. i.e. the following works:
int main(void)
{
int array[20] = {0};
int i=0;
while(scanf("%d", &array[i++]) == 1);
return 0;
}
As BLUEPIXY says, you must enter the correct keystroke for EOF.
来源:https://stackoverflow.com/questions/25141168/how-to-get-integer-input-in-an-array-using-scanf-in-c