C, flushing stdin

天涯浪子 提交于 2019-11-28 00:21:52

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

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;
}

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;
        }
    };
}

Have a look at fpurge:

fpurge(stdin);
xpmatteo

Try:

fgets(str, 2000, stdin)

Then truncate str to 19 :-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!