There are two things you have to pay attention to (taken from scanf(2)'s man page):
- scanf reads until it finds whitespace (space, newline, etc.).
- If a pattern is not matched, scanf stops reading the input.
Say I have the following code:
while(1) {
int ret, i1, i2;
scanf("%d %d", &i1, &i2);
if(i1 == 1 && i2 == 2)
break;
}
If I give the string "1 b\n" as input (remeber the "enter" key is used to flush the terminal buffer but it is also present on the input), this is what happens:
Code: Select all
- Input string:
inputstring = "1 b\n";
- scanf tries to read the first part of the pattern ("%d") and is successful, yielding (roughly):
i1 = 1;
inputstring = " b\n";
- scanf tries to read the second part of the pattern (" ") and is successful, so the space is removed from the buffer.
inputstring = "b\n";
- scanf tries to read the third part of the pattern ("%d"), but fails. The input is unchanged.
This will leave the buffer as "b\n". You can check this by putting this before the end of the loop:
char buffer[1024];
scanf("%s", &buffer);
printf("--%s--\n", buffer);
scanf("%s", &buffer);
printf("--%s--\n", buffer);
What happened here is the first scanf read the remaing "b" on the input and stopped at the newline (whitespace). The second scanf started reading, got the newline and stopped at the end of the input.
But consider what happens if you don't include these two scanf's. The input buffer still contains "b\n" and we are back at the head of the loop. scanf will try to read the first pattern ("%d"), fail and bail out, because of the first rule on the beginning of this post. The test will keep failing, because i1 and i2 still have their old values (1 and undefine, respectively). Bottom line: you're stuck on an infinite loop.