【问题标题】:While Loop skipping scanf for it's condition.While 循环跳过 scanf 的条件。
【发布时间】:2012-12-10 04:01:48
【问题描述】:

我不明白为什么 While 循环只是加快速度并跳过 char 的 scanf? 它甚至不会询问我的意见,只是像没有明天一样循环。

#include <stdio.h>


int main()
{
    int number;
    int multiply, ans;
    char choice;

    printf("-------------------------------------");
    printf("\n      MULTIPLICATION TABLE           ");
    printf("\n-------------------------------------");


    do
    {

         printf("\nEnter an integer number:");
         scanf("%d", &number);


        printf("\nMultiplication of %d is :-\n", number);
        printf("\n");

        for(multiply=1; multiply<11; multiply++){
            ans = number * multiply;
            printf(" %d", ans);
        }

        printf("\n");
        printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
        scanf("%c", &choice);
        printf("\n");

    } 
    while(choice='Y');

    printf("Thank You");
    return 0;

}

【问题讨论】:

    标签: c loops while-loop char


    【解决方案1】:

    scanf() 不会做你认为的事情(换行符、缓冲等)。最好使用fgetc()

    choice = fgetc(stdin);
    

    出于同样的原因,您需要去掉尾随的换行符

    scanf("%d", &number");
    

    离开标准输入缓冲区。要解决此问题,请插入

    fgetc(stdin);
    

    在对 scanf() 的特定调用之后。

    另外,C 不是 Pascal。您正在寻找的相等比较运算符和条件是

    while (choice == 'Y')
    

    单个等式标记表示赋值。

    【讨论】:

    • @DCoder 并且修复它并不能修复关于 scanf() 的错误假设。
    • 已更改但仍跳过输入部分。
    • @user1924648 你在使用什么样的疯狂输入数据?尝试在scanf("%d", &amp;number); 之后插入另一个对fgetc() 的调用?
    • @user1924648 是的,它成功了,我也试过了。
    【解决方案2】:

    我认为您需要使用== 运算符在while 条件检查中进行比较:

       while(choice=='Y');
    

    当前您正在使用= 运算符,它将Y 分配给choice 变量。

    【讨论】:

    • 我已经修复了那个部分,但它仍然不会等待我输入。
    • @user1924648 使用fgetc(),真的。
    • 使用了 fgetc() ,现在它已经退出循环,无需等待我输入任何内容。它现在可以工作了,我只是在获取 int 后插入了一个额外的 fgetc。
    【解决方案3】:

    我已经很久没有用那种语言编程了,但乍一看,你有:

    while(choice='Y');
    

    代替:

    while(choice=='Y');
    

    == 比较,= 设置等于。因此,while 循环实际上并没有检查您要设置的条件。

    【讨论】:

    • “我已经修复了那个部分,但它仍然不会等待我输入。– user1924648 1 分钟前”
    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 2016-06-05
    • 2020-03-11
    • 1970-01-01
    • 2015-03-11
    • 2010-12-12
    相关资源
    最近更新 更多