简体   繁体   English

根据用户输入重复while循环

[英]Repeat while loop according to the user input

#include<stdio.h>
void main(){
    char choice1,choice2;
    int a,b,c;
    while(choice1 != 'n'){
        printf("Enter + for addition:\n");
        printf("Enter - for substraction:\n");
        printf("Enter * for multiplication:\n");
        printf("Enter / for division:\n");
        scanf("%c",&choice2);
        printf("Enter two numbers:\n");
        scanf("%d %d",&a,&b);
        if (choice2 == '+'){
            c=a+b;
            printf("Addition = %d",c);
        }
        else if (choice2 == '-'){
            c=a-b;
            printf("Substraction = %d",c);
        }
        else if (choice2 == '*'){
            c=a*b;
            printf("Multiplication = %d",c);
        }
        else if (choice2 == '/'){
            c=a/b;
            printf("Division = %d",c);
        }
        else{
            printf("Invalid choice!");
        }
        printf("\nEnter y to continue and n to exit:\n ");
        scanf("%c",&choice1);
    }
}

When I run the above program, the while loop repeats without taking the value of choice1 from the user. 当我运行上面的程序时,while循环会重复,而不会从用户那里获取choice1的值。 Can anyone please tell me what is wrong in the above code??? 谁能告诉我以上代码有什么问题吗???

choice1 is compared without initializing in the expression choice1 != 'n' . choice1而不在表达初始化进行比较choice1 != 'n' Use do while loop instead or change it as follows 使用do while循环代替或如下更改

scanf(" %c",&choice1);
while(choice1 != 'n'){  
     // Loop body

      scanf(" %c",&choice1); // Do not forget to add a space before %c to skip newline 
                             //characters left behind by previous call to scanf.
}

well yes choice1 is uninitialized and you are also ignoring the return values of your scans. 好吧,choice1未初始化,您也忽略了扫描的返回值。

But to answer YOUR question. 但是要回答您的问题。 Your problem is that choice1 gets the value '\\n' after scanning not 'n' as you might think, because '\\n' is before 'n' in the buffer, 您的问题是,choice1扫描后的值不是您可能认为的'n',因此它的值是'\\ n',因为'\\ n'在缓冲区中的'n'之前,

so use getchar() before you scan for choice1 at the end, and it will work. 因此,在扫描最后的choice1之前,请使用getchar(),它将起作用。

I mean do this: 我的意思是这样做:

getchar();

scanf("%c", &choice1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM