Most scanf
specifiers will leave a newline pending in the input stream.
Thus immediately following a scanf
, fgetc
will consume a newline.
The best I can come up with is to use the scanset %1[\n]
to scan a single newline. Scan for the newline afterwards to consume the pending newline and scan before the desired input to get the leading newline that indicates input is complete and exit the loop.
The second loop accomplishes the same effect using fgets
.
#include <stdio.h>
#include <stdlib.h>
#define LINE 99
//stringify to use in format string
#define SFS(x) #x
#define FS(x) SFS(x)
int main ( void) {
char text[LINE + 1] = "";
char newline[2] = "";
int result = 0;
while ( 1) {
printf ( "enter text for scanf\n");
scanf ( "%*[ \t\r]"); // scan and discard spaces, tabs, carriage return
if ( 1 == ( result = scanf ( "%1[\n]", newline))) {
printf ( "\tscanned leading newline\n");
break;
}
if ( 1 == ( result = scanf ( "%"FS(LINE)"[^\n]", text))) {
//as needed parse with sscanf, strtol, strtod, strcspn, strspn, strchr, strstr...
printf ( "\tscanned text: %s\n", text);
scanf ( "%*[ \t\r]"); // scan and discard spaces, tabs, carriage return
if ( 1 == scanf ( "%1[\n]", newline)) {
printf ( "\tscanned trailing newline\n");
}
}
if ( EOF == result) {
fprintf ( stderr, "EOF\n");
return 1;
}
}
while ( 1) {
printf ( "enter text for fgets\n");
if ( fgets ( text, sizeof text, stdin)) {
if ( '\n' == text[0]) {
printf ( "----newline only\n");
break;
}
printf ( "----text is:%s\n", text);
//as needed parse with sscanf, strtol, strtod, strcspn, strspn, strchr, strstr...
}
else {
fprintf ( stderr, "EOF\n");
return 2;
}
}
return 0;
}