A part of the code I'm writing has to read a sequence of integers separated by a space from input into an array.
It works fine when I input, for example, 3 numbers, and then press Enter. But if after inputting the numbers I press Space and then Enter, it goes to new line and waits for me to input more numbers.
How can I avoid this?
#include <stdio.h>
#include <stdbool.h>
#define MAX_VALUES 250000
int main()
{
int sequence[MAX_VALUES];
int count = 0;
do {
scanf("%d", &sequence[count++]);
}
while(getchar() != '\n');
for(int i = 0; i < count; i++) {
printf("Element is: %d\n", sequence[i]);
}
return 0;
}
Just think about what your code does, e.g. for the following input:
1 \n.scanfconsumes1getcharconsumesscanfsees\nand will wait until a number arrives.That is why you are seeing this undesired behavior.
A simple way to fix this would be to check for and skip spaces after each
scanf: