Mittwoch, 23. März 2011

fscanf() and scanf() with %c

fscanf() and scanf() with %c

When the first format specification in a scanf() uses %c or edit set conversion code, any return character left in the buffer by a previous scanf operation MUST be manually consumed 硬食.

scanf(" %c %d", &aChar, &num1); /*put a whitespace char. at the beginning */

1. The input stream is buffered. the OS does NOT pass the input stream until we press the return key. This means that there is ALWAYS a return character at the end of the system.

2. scanf() leaves the return character in the buffer by default. If we want the buffer to be empty, e must read the return character and DISCARD 丟棄 it.

3. We read it with %c with a suppress flag, ie., %*c. When the return character remains in the buffer, the NEXT scanf() DISCARDS 丟棄 it for all conversion codes EXCEPT character and scan set.

4. Alternatively, we can force it to be discarded by placing a SPACE at the beginning of the format string or before a conversion specification.

5. scanf() and fscanf() does not terminate until the format string is exhausted, ie., until all specified operations are complete.

6. Whitespace characters in the format string cause whitespace characters in the buffer to be read and discarded 丟棄.

7. When a whitespace character occurs at the END of the format string, scanf() reads and DISCARDS 丟棄 the return character in the buffer and then waits for more input.

8. scanf() cannot terminate UNTIL it finds a non-whitespace character.

Keine Kommentare: