Konno__Yuuki 2021-10-30 21:13 采纳率: 78.6%
浏览 35

为什么这个地方的“\n“没有被消除?

img

第一次输入没问题,第二次的时候局部变量choice为”\n" 然而代码中已经使用了while((ch = getchar())!='\n')

完整代码如下:

#include<stdio.h>
char menu(void);
void af(char n);
double inp2(void);
int main(void)
{
    char choice;
    choice = menu();
    while(choice != 'q')
    {
        switch(choice)
    {
    case 'a':
        af('a');
        break;
    case 's':
        af('s');
        break;
    case 'm':
        af('m');
        break;
    case 'd':
        af('d');
        break;
    //default:
    //    printf("Please enter a valid letter,such as a,s,m or d:");
    }
    choice = menu();
    }
    return 0;
}
char menu(void)
{
    printf("Enter the operation of your choice:\n");
    printf("a.ad               s.subtract\n");
    printf("m.multiply         d.divide\nq.quit\n");
    char choice;
    scanf("%c",&choice);
    char ch;
    while((ch = getchar()) != '\n')
        continue;
    return choice;
}
void af(char n)
{
    printf("Enter first number:");
    double a;
    a = inp2();
    printf("Enter second number:");
    double b;
    b = inp2();
    while(n == 'd' && b == 0)
    {
        printf("Enter a number other than 0:");
        b = inp2();
    }
    if(n == 'a')
    printf("%g + %g = %g\n",a,b,a+b);
    else if(n == 's')
    printf("%g - %g = %g\n",a,b,a-b);
    else if(n == 'm')
    printf("%g * %g = %g\n",a,b,a*b);
    else if(n == 'd')
    printf("%g / %g = %g\n",a,b,a/b);
}
double inp2(void)
{
    double num;
    if(scanf("%lf",&num) != 1)
    {
        char ch;
        while((ch = getchar()) != '\n')
            putchar(ch);
        printf(" is not an number.\n");
        printf("Please enter a number, such as 2.5,-1,78E8,or3:");
        num = inp2();
    }
    return num;

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2021-10-30 23:25
    关注

    menu()函数这么改:

    char menu(void)
    {
        printf("Enter the operation of your choice:\n");
        printf("a.ad               s.subtract\n");
        printf("m.multiply         d.divide\nq.quit\n");
        char choice[2]={0};
        scanf("%s",choice);
        return choice[0];
    }
    
    
    评论

报告相同问题?

问题事件

  • 创建了问题 10月30日

悬赏问题

  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错