problem in scanning character in C
#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 input
Unable to scan input given by user??????
thanks..
Unlike most conversions, %c
does not skip 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 %c
reads.
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.
It's getting the newline character from your previous data entry. Look into using fgets()
and sscanf()
instead of using scanf()
directly.
Here in this statement write %s
instead of %c
. It will surely work.
scanf("%s",&ch);
in this problem you can write like this scanf(" %c",&ch);
a space will cover your "Enter" character,then it scan's the input that you want...https://ide.geeksforgeeks.org/ANGPHrqeAq
If you're just reading in a single character, you could just use getchar()
-
c = getchar();
Use getchar()
or sscanf()
whichever comforts more.
Like
char ch;
ch = getchar();
This is simple. also if you want to use scanf("%c",&ch);
then,
just remove the \n
from your previous printf()
statement.
For a single character input, use getchar()
.
精彩评论