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

标签 c while-loop printf scanf eof

我希望在用户决定用 (Ctrl+d) 结束它之前询问用户他们想写“多少圈”,这是 EOF?

额外的问题:如果我写一个字母,例如“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;
}  

最佳答案

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

  • 您的代码会 self 重复 - 如果可能,您应该统一处理第一次迭代和后续迭代的代码。
  • 您的代码不会处理无效输入 - 当最终用户输入非数字数据时,您的程序会进入无限循环。
  • 您的代码遵循旧的 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;

关于c - 用ctrl+d结束while循环,scanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30304368/

相关文章:

loops - 哪个是更好的做法 - 带中断或条件循环的 for 循环?

python - 文件保存问题 PYTHON - 重复文件?

c - 解释c程序的输出

c - 使用 memcpy 时出现意外结果

Java 日志记录框架 - 支持 printf()

c - Linux 和 C 中的 SPI 超时

c - 尝试创建一个程序来计算系列 𝑆 = 1^2 - 2^2 + 3^2

c - 引用 C#define 从运行时参数

python - 创建奇数索引python的总和

c - 在 epoll 的事件结构中使用 void ptr