Scanf Input Digestion

Input digestion with scanf

void digestline(void) {
scanf("%*[^\n]"); /* Skip to the End of the Line */
scanf("%*1[\n]"); /* Skip One Newline */

This function is taken from Weiss pg. 341. Using assignment suppression, we can use * to suppress anything contained in the set [^\n]. This skips all characters until the newline. The next scanf allows one newline character read. Thus we can digest bad input!


Scanf alternatives

One of the alternatives to scanf/fscanf is fgets. The prototype is:
char *fgets(char *s, int size, FILE *stream);

fgets reads in size - 1 characters from the stream and stores it into *s pointer. The string is automatically null-terminated.
fgets stops reading in characters if it reaches an EOF or newline.
Now that you've read characters of interest from a stream, what do you do with the string? Simple! Use sscanf, see below.


With fgets, we have to specify the size of the buffer, n. This function reads up through and including the next newline, but no more than n1 characters, into the buffer. The buffer is terminated with a null byte. If the line, including the terminating newline, is longer than n1, only a partial line is returned, but the buffer is always null terminated. Another call to fgets will read what follows on the line.
Source: Advanced Programming in UNIX, 2nd edition

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License