首页 > 解决方案 > C语言中的Swtich案例问题

问题描述

我在代码中的嵌套 switch 语句的帮助下制作了一个迷你项目 ic错误在代码的第 15 行,这里%c不工作但%s工作,请帮我解决这个查询并告诉我如何使用%c运行此代码这是我的代码:-

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,ch;
char choice;
clrscr();
printf("1.Calculator\n2.Convrter\n\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
    case 1:printf("1.Addition(A)\n2.Subtraction(S)\n3.Multiplication(M)\n4.Division(D)\n5.Module(P)\n\n");
    printf("Enter your choice : ");
    **scanf("%c",&choice);**
    switch(choice)
    {
    case 'A':printf("Provide the value of a : ");
    scanf("%d",&a);
    printf("Provide the value of b : ");
    scanf("%d",&b);
    printf("\n");c=a+b;
    printf("%d",c);
    break;
    case 'S':printf("Provide the value of a : ");
    scanf("%d",&a);
    printf("Provide the value of b : ");
    scanf("%d",&b);
    printf("\n");c=a-b;
    printf("%d",c);
    break;
    case 'M':printf("Provide the value of a : ");
    scanf("%d",&a);
    printf("Provide the value of b : ");
    scanf("%d",&b);
    printf("\n");c=a*b;
    printf("%d",c);
    break;
    case 'D':printf("Provide the value of a : ");
    scanf("%d",&a);
    printf("Provide the value of b : ");
    scanf("%d",&b);
    printf("\n");c=a/b;
    printf("%d",c);
    break;
    case 'P':printf("Provide the value of a : ");
    scanf("%d",&a);
    printf("Provide the value of b : ");
    scanf("%d",&b);
    printf("\n");c=a%b;
    printf("%d",c);
    break;
    default:printf("Invalid Input");
    }
    break;
}
getch();
}

标签: cswitch-statement

解决方案


上一次调用scanf()

scanf("%d",&ch);

\n在第 10 行中,将由按下 Enter/Return生成的换行符 ( ) 留在内stdin

这个换行符在第二次scanf()调用时被读取,因为%c格式/转换说明符不会忽略前导空格并且还会读取/使用不可打印的字符。

只需在转换说明符之前插入空格%c

scanf(" %c",&choice);

捕捉该换行符或任何前导空格。


推荐阅读