You can figure out what happens by modifying your code as follows:
#include <stdio.h>
int main(){
char str1[3];
while( 1 ){
scanf("%2s", str1);
printf("test: %s\n", str1);
}
}
which simply prints the contents of the str1
alongside of the "test" string.
Here is an example output for an input string of 1234567
:
1234567
test: 12
test: 34
test: 56
test: 7
The scanf("%2s", str1);
statement reads two characters from the stdin
and assings them to the str1
. The read characters are "popped" from the input stream, i.e., they are removed. If the stdin
happens to contain more characters, the excess ones are left untouched. Therefore, for the given input, when the first scanf
is returned, the str1
containes 12\0
, and the stdin
contains 34567
.
Since these are in the infinite loop, the code repeats, scanf
gets called again, reading the first two characters from the stdin
again, only this time finds 34
.
And the process repeats, untill there are no characters left on the stdin
, then the scanf
waits for the user input, presumably as you would have expected.
Basically, scanf
keeps reading instead of waiting for user input, since the stdin
already contains something to read.
So for example, when I entered two characters, it printed "test" two times.
This on the other hand, does not make sense, as it should be printing "test" for N/2 times, rounded up, where N is the number of characters you enter.
There is not much that I can suggest for "fixing this", since it is not really clear what you are expecting. But if you want to get rid of the remaining characters in the stdin
, you can check this.