用ctrl + d结束while循环,scanf?

时间:2015-05-18 13:21:51

标签: c while-loop printf scanf eof

我希望用户被问到他们想写的“圈数”,直到用户决定用( Ctrl + d )EOF结束它? / p>

额外的问题:如果我写一封信,例如“k”,它会垃圾邮件圈出来。我该如何改变?

#include <stdio.h>
int main ()
{
    int i;
    int x;

    printf("\nHow many circles do you want to write?\n");
    scanf("%d", &x);

    while(x != EOF)
    {
        for (i = 1; i <= x; i = i + 1)
        {
            putchar('o');
        }
        printf("\nHow many circles do you want to write?"
               "(to end program click ctrl+d at the same time!))\n");
        scanf("%d", &x);
    }
    printf("\n\n Bye! \n\n");
    return 0;
}  

4 个答案:

答案 0 :(得分:2)

您的计划遇到的最大问题是scanf不会将EOF读入变量。但是,解决这个问题不会使您的程序完全正确,因为您的代码中还有其他问题:

  • 您的代码会自行重复 - 如果可能,您应该统一处理第一次迭代和后续迭代的代码。
  • 您的代码无法处理无效输入 - 当最终用户输入非数字数据时,您的程序会进入无限循环。
  • 您的代码遵循旧的C风格 - 声明顶部的所有变量都不需要超过十五年。你应该在循环中声明你的循环变量。

以下是解决所有这些缺点的方法:

int x;
for (;;) {
    printf("\nHow many circles do you want to write? (to end the program click Ctrl+D at the same time!)\n");
    int res = scanf("%d", &x);
    if (res == EOF) break;
    if (res == 1) {
         ... // Draw x circles here
    } else {
        printf("Invalid input is ignored.\n");
        scanf("%*[^\n]");
    }
}
printf("\n\n Bye! \n\n");
return 0;

答案 1 :(得分:0)

根据man pagescanf()return EOF,而不是scan EOF到x作为值。

  

返回值

     

这些函数返回成功匹配和分配的输入项的数量,可以少于提供的数量,或者在早期匹配失败的情况下甚至为零。

     

如果在第一次成功转换或匹配失败发生之前达到输入结束,则返回值EOF ......

此外,

  

如果我写一封信,例如&#34; k&#34;它将垃圾邮件圈出来,我该如何更改?

如果输入一个char值,则会导致匹配失败,在您的情况下,scanf()会返回0,而不是1

所以,总而言之,您已收集scanf()返回值,并检查该值是否符合所需条件。您可以将代码更改为

int retval = 0;
while ((retval = scanf("%d", &x))!= EOF && (retval == 1))

答案 2 :(得分:0)

如果你被允许#include,有两个方便的函数bool kbhit()和char getch()。 所以你可以写

syn mis non syn mis non syn mis non syn mis non
    A       A       A       C       C       C       T       T       T       G       G       G
A   0.24    0.38    0.38    0.36    0.14    0.50    0.19    0.31    0.50    0.50    0.17    0.33
C   0.22    0.44    0.33    0.31    0.12    0.56    0.25    0.58    0.17    0.08    0.17    0.75
G   0.28    0.36    0.36    0.80    0.10    0.10    0.38    0.08    0.54    0.27    0.64    0.09
T   0.24    0.41    0.35    0.60    0.33    0.07    0.43    0.43    0.14    0.55    0.27    0.18

提示:看一下输入字母而不是数字时返回的scanf(%d,&amp; x)。

答案 3 :(得分:0)

您可以通过char输入读取char:

<form>
    <input type="checkbox" name="whatever" value="1" required="required" class="required_group" />
    <input type="checkbox" name="whatever" value="2" required="required" class="required_group" />
    <input type="checkbox" name="whatever" value="3" required="required" class="required_group" />
    <input type="checkbox" name="whatever" value="4" required="required" class="required_group" />
    <input type="submit" name="submit" />
</form>
相关问题