C中扫描字符的问题
#include #include void main() { int a,b,c; char ch; printf("Enter value of a and b"); scanf("%d %d",&a,&b); printf("Enter choice of operation"); scanf("%c",&ch);// **Here this statment is not able to receive my input*** switch(ch) { case '+': c=a+b; break; case '-': c=ab; break; default: printf("invalid"); break; } getch(); }
错误:
scanf("%c",&ch);
// 这里这个声明无法接收我的输入无法扫描用户给出的输入??????
谢谢..
与大多数转换不同, %c
在转换字符之前不会跳过空格。 在用户输入两个数字后,在输入缓冲区中等待读取的回车符/换行符 – 这就是%c
读取的内容。
它从您之前的数据输入中获取换行符。 查看使用fgets()
和sscanf()
而不是直接使用scanf()
。
在此语句中写入%s
而不是%c
。 它肯定会奏效。
scanf("%s",&ch);
试试scanf(" %c", &ch);
这是因为你的scanf将第二个数字后面的空格视为要插入ch的字符。
对于单个字符输入,请使用getchar()。
如果你只是在单个字符中阅读,你可以使用getchar()
–
c = getchar();
使用getchar()
或sscanf()
更舒适。
喜欢
char ch; ch = getchar();
这很简单。 如果你想使用scanf("%c",&ch);
然后,只需从之前的printf()
语句中删除\n
。
在这个问题中你可以这样写一下scanf(“%c”,&ch);
一个空格将覆盖你的“Enter”字符,然后它扫描你想要的输入… https://ide.geeksforgeeks.org/ANGPHrqeAq