c - 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();
}
解决方案
上一次调用scanf()
:
scanf("%d",&ch);
\n
在第 10 行中,将由按下 Enter/Return生成的换行符 ( ) 留在内stdin
。
这个换行符在第二次scanf()
调用时被读取,因为%c
格式/转换说明符不会忽略前导空格并且还会读取/使用不可打印的字符。
只需在转换说明符之前插入空格%c
:
scanf(" %c",&choice);
捕捉该换行符或任何前导空格。
推荐阅读
- c++ - 在 C++ 中使用运算符重载显示不正确的结果
- angular-httpclient - 用于在下拉列表中显示文件名列表的 http.get() 方法
- pytorch - Pytorch(火炬脚本)错误:“NoneType”类型的属性“downsample”在脚本方法中不可用(您是否忘记添加它__constants__?)
- jenkins - 缺少必需的上下文类 hudson.FilePath 也许您忘记用提供此功能的步骤包围代码,例如:节点
- c# - 在实体框架中定义嵌套派生表
- c# - 在 asp.net 网络表单中获取消息的网页导航被取消
- java - Wiremock 日期格式
- excel - 为什么我的单元格输出变成这样 =SUM('J2':'J13')-SUM('AB2':'AB13')
- r - 如何编写条件(如果,否则)以根据用户输入显示 ui 元素?
- nginx - 如何在 nginx 中监听 2 个端口?