DoggyDoo
DoggyDoo

Reputation: 63

C, flushing stdin

i have a problem with the use of fgets. The loop is supposed to read a line of max. 19 characters, analyze this char array and then wait for next input. The problem is that if the line entered exeeds 19 characters, fgets will fill str with the remaining characters untill Ctrl-D or newline is entered, thus initiating a new loop without new input. The input (stdin) should in some way be flushed after 19 characters are read, so the loop can start with a clean slate. Anyone have a solution to this?

 char str[20];
 while((fgets(str, 20, stdin) != NULL)) {
  puts(str);        //monitoring str

  if(str[0] == 'q') break;
 }

Example in use:

hola hola                        //user inputs 9 chars + newline
hola hola                        //puts writes

hoo hoo hoo hoo hooh             //user inputs 20 chars + newline
hoo hoo hoo hoo hoo              //puts writes
h                                //

Upvotes: 4

Views: 4853

Answers (5)

xpmatteo
xpmatteo

Reputation: 11408

Try:

fgets(str, 2000, stdin)

Then truncate str to 19 :-)

Upvotes: -2

coderaj
coderaj

Reputation: 101

Have a look at fpurge:

fpurge(stdin);

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363567

char str[21];  /* read one extra character */
while (fgets(str, 21, stdin) != NULL) {
    /* if line too long, truncate and swallow the rest of the line */
    if (strlen(str) > 19) {
        str[19] = '\0';
        while (getchar() != '\n' && !feof(stdin))
            ;
    }

    puts(str);
    if(str[0] == 'q') break;
}

Upvotes: 2

kriss
kriss

Reputation: 24177

Another possible variant with constraint of fgets() being the only input used and at loop level. It's definitely very similar to what larsman proposed. So I suppose I will vote for him :-)

#include <stdio.h>

int main(){
    char str[20];
    int skip = 0;
    str[19] = 1;
    while (fgets(str, 20, stdin)) {
        // just ignore lines of more than 19 chars
        if (str[19] == 0){
            str[19] = 1;
            skip = 1;
            continue;
        }
        // also skip the end of long lines
        if (skip) {
            skip = 0;
            continue;
        }
        // monitor input
        puts(str);
        // stop on any line beginning with 'q'
        if (str[0] == 'q'){
            break;
        }
    };
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

scanf("%*[^\n]\n"); is probably one of the simplest possibilities.

Upvotes: 6

Related Questions