C语言 C中扫描字符的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5109512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
problem in scanning character in C
提问by Viral Parmar
#include<stdio.h>
#include<conio.h>
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=a-b;
break;
default:
printf("invalid");
break;
}
getch();
}
Error:
错误:
scanf("%c",&ch);// Here this statment is not able to receive my inputUnable to scan input given by user??????
scanf("%c",&ch);//这里这个语句无法接收我的输入无法扫描用户给出的输入??????
thanks..
谢谢..
回答by Jerry Coffin
Unlike most conversions, %cdoes notskip whitespace before converting a character. After the user enters the two numbers, a carriage return/new-line is left in the input buffer waiting to be read -- so that's what the %creads.
不像大多数的转换,%c也不能转换字符之前跳过空白。用户输入两个数字后,回车/换行符会留在输入缓冲区中等待读取——这就是%c读取的内容。
回答by Carl Norum
It's getting the newline character from your previous data entry. Look into using fgets()and sscanf()instead of using scanf()directly.
它从您之前的数据输入中获取换行符。研究 usingfgets()和sscanf()而不是scanf()直接使用。
回答by Apoorva Iyer
Just try
scanf(" %c", &ch);This is because your scanf is treating the whitespace after the second number as the character to be inserted into ch.
试试吧
scanf(" %c", &ch);这是因为您的 scanf 将第二个数字之后的空格视为要插入到 ch 中的字符。
回答by rabindra chauhan
Here in this statement write %sinstead of %c. It will surely work.
在此语句中写%s而不是%c. 它肯定会起作用。
scanf("%s",&ch);
回答by Dishant J
Use getchar()or sscanf()whichever comforts more.
使用getchar()或sscanf()以更舒适的方式使用。
Like
喜欢
char ch;
ch = getchar();
This is simple. also if you want to use scanf("%c",&ch);then,
just remove the \nfrom your previous printf()statement.
这很简单。此外,如果您想使用scanf("%c",&ch);then,只需\n从之前的printf()语句中删除。
回答by Masidul Hasan
in this problem you can write like this scanf(" %c",&ch);
在这个问题中你可以这样写 scanf(" %c",&ch);
a space will cover your "Enter" character,then it scan's the input that you want...https://ide.geeksforgeeks.org/ANGPHrqeAq
一个空格将覆盖您的“Enter”字符,然后它会扫描您想要的输入... https://ide.geeksforgeeks.org/ANGPHrqeAq
回答by Wipqozn
If you're just reading in a single character, you could just use getchar()-
如果您只是阅读单个字符,则可以使用getchar()-
c = getchar();
回答by karlphillip
For a single character input, use getchar().
对于单个字符输入,请使用getchar().

