Linux,scanf in循环,而stdin已经加载

时间:2017-01-30 22:35:39

标签: c linux

我在使用scanf和linux上的循环时遇到了麻烦。

#include <stdio.h>
#include <stdlib.h>
#include <stdio_ext.h>

int main(int argc, char ** argv){
    int i = 0;
    char s[255];
    char c;

    while(i<10){
        printf("Here : ");
        scanf(" %s", s);
        printf("%s\n", s);
        i++;
        while((c = getchar()) != '\n' && c != EOF);
    }

    return EXIT_SUCCESS;
}

如果在shell Linux中,如果我执行我的文件:

echo "lol" | ./testWhileScanf

然后结果将是:

  

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

     

这里:lol

我不知道为什么这是结果,我的代码的一行是刷新stdin,没有这种问题。

寻求我尝试的解决方案: __ fpurge fpurge fflush 但都没有效果。

我只想得到:

  

在这? :lol

     

在这? :

等待输入。 当然我在这里遗漏了一些东西..但我无法弄清楚= /

1 个答案:

答案 0 :(得分:4)

致电时

scanf(" %s", s);

第一次将s设置为lol,然后返回1。当您第二次调用它时,没有进一步的输入,因此scanf在不设置变量的情况下返回零。但是,您的代码会忽略scanf的返回值,并且无论如何都会打印s

添加支票和break可以解决此问题:

if (scanf(" %254s", s) != 1) break;

请注意格式字符串中的大小限制器,它会阻止scanf导致缓冲区溢出。