#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().
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed last month.
int main ()
{
char c;
int choice,dummy;
do{
printf("1. Print Hello\n2. Print World\n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello\n");
break;
case 2:
printf("World\n");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice\n5");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
tried removing int dummy variable and dummy input, program exits without taking any character input. how is this helping the code to not to exit ?
Whoever wrote this doesn't understand how scanf format specifiers work.
The first call to scanf uses the %d format specifier. This reads and discards any leading whitespace, then reads a decimal integer. Assuming you pressed ENTER after typing in this integer, a newline character will be left in the input buffer.
The %c format specifier reads the first character in the input buffer but does not strip off trailing whitespace. So without the prior call reading dummy, this will read the newline that was stuck in the input buffer previously into c. That causes the comparison c=='y' to be false so the loop exits..
The extra call to scanf for dummy reads and discards the newline left in the input buffer and wait for an integer to be read. Presumably, the user will enter y or n given the prompt, so that call to scanf will not read anything more and will return 0, indicating that nothing matched. The following scanf then reads the y or n.
The proper way to handle this is to add a space before the %c format specifier to absorb leading whitespace instead of adding a "dummy" call:
printf("do you want to enter more?");
scanf(" %c",&c);
The scanf("%d",&dummy) removes a newline so the subsequent scanf("%c",&c); works. Otherwise, it will take \n as its character.
The "extra" newline comes from the fact that it is left in the input stream by the original: scanf("%d",&choice);
To fix, remove the dummy related code and do:
scanf(" %c",&c);
Note the preceding space in the format. This tells scanf to skip over whitespace (which includes newlines).
The fully corrected code is:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char c;
int choice;
do {
printf("1. Print Hello\n2. Print World\n3. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Hello\n");
break;
case 2:
printf("World\n");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice\n5");
}
printf("do you want to enter more?");
scanf(" %c", &c);
} while (c == 'y');
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1;
int num2;
char op;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter an operator: ");
scanf("%c", &op);
printf("Enter the second number: ");
scanf("%d", &num2);
switch(op){
case'+':
printf("%d", num1+num2);
break;
case'-':
printf("%d", num1-num2);
break;
case'/':
printf("%d", num1/num2);
break;
case'*':
printf("%d", num1*num2);
break;
default:
printf("Enter a valid Operator");
}
return 0;
}
I tried to build a basic calculator with user input. but I am getting an error in this line scanf("%c", &op); I searched in here(Stackoverflow) and I also found the answer that if I put a space in scanf(" %c", &op) then my program will work fine;
now the question I have is, Could someone explain me this in laymen's terms for a beginner? Please. Your answer will be much appreciated
scanf manual:
specifier c:
Matches a sequence of characters whose length is specified by the
maximum field width (default 1); the next pointer must be a pointer to
char, and there must be enough room for all the characters (no
terminating null byte is added). The usual skip of leading white space
is suppressed. To skip white space first, use an explicit space in the
format.
ie format scanf(" %c", &op).
After typing the first number for int num1 you type an enter '\n' the next scan for character captures the new line and prints it . So as per the manual, To skip white space first, use an explicit space in the format:
printf("Enter an operator: ");
scanf(" %c", &op);
or use like this below:
printf("Enter an operator: ");
scanf("%c", &op);
scanf("%c", &op);
Prepend the conversion specifier in the format string with a space like
scanf( " %c", &op );
^^^^^
In this case white space characters in the input stream as the new line character '\n' that corresponds to the pressed key Enter will be skipped
The problem is not with scanf but stdin. stdin and stdout refer to the same file in the memory for console application. So there is '\n' in the stdin which you have entered for first scanf which is taken by scanf and stored in op. Try putting scanf("%c", &op); above scanf("%d", &num1); or write fflush(stdin) above scanf("%c", &op);
Try using 'getc' and 'gets' instead.
'scanf' is considered to be unsafe altogether and it would be wise to search for safer alternatives. That way you will have greater control over user input.
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working.
I am not able to figure out the root cause of the issue, can anyone please help me.
#include<stdio.h>
int main()
{
int x, n=0, p=0,z=0,i=0;
char ch;
do
{
printf("\nEnter a number : ");
scanf("%d",&x);
if (x<0)
n++;
else if (x>0)
p++;
else
z++;
printf("\nAny more number want to enter : Y , N ? ");
ch = getchar();
i++;
}while(ch=='y'||ch=='Y');
printf("\nTotal numbers entered : %d\n",i);
printf("Total Negative Number : %d\n",n);
printf("Total Positive number : %d\n",p);
printf("Total Zero : %d\n",z);
return 0 ;
}
The code has been copied from the book of "Yashvant Kanetkar"
I think, in your code, the problem is with the leftover \n from
scanf("%d",&x);
You can change that scanning statement to
scanf("%d%*c",&x);
to eat up the newline. Then the next getchar() will wait for the user input, as expected.
That said, the return type of getchar() is int. You can check the man page for details. So, the returned value may not fit into a char always. Suggest changing ch to int from char.
Finally, the recommended signature of main() is int main(void).
That's because scanf() left the trailing newline in input.
I suggest replacing this:
ch = getchar();
With:
scanf(" %c", &ch);
Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than consuming a single char in the previous scanf() because it ignores any number of blanks.
When the user inputs x and presses enter,the new line character is left in the input stream after scanf() operation.Then when try you to read a char using getchar() it reads the same new line character.In short ch gets the value of newline character.You can use a loop to ignore newline character.
ch=getchar();
while(ch=='\n')
ch=getchar();
When you using scanf getchar etc. everything you entered stored as a string (char sequence) in stdin (standard input), then the program uses what is needed and leaves the remains in stdin.
For example: 456 is {'4','5','6','\0'}, 4tf is {'4','t','f','\0'} with scanf("%d",&x); you ask the program to read an integer in the first case will read 456 and leave {'\0'} in stdin and in the second will read 4 and leave {''t','f',\0'}.
After the scanf you should use the fflush(stdin) in order to clear the input stream.
Replacing ch = getchar(); with scanf(" %c", &ch); worked just fine for me!
But using fflush(stdin) after scanf didn't work.
My suggestion for you is to define a Macro like:
#define __GETCHAR__ if (getchar()=='\n') getchar();
Then you can use it like:
printf("\nAny more number want to enter : Y , N ? ");
__GETCHAR__;
I agree that it is not the best option, but it is a little bit more elegant.
Add one more line ch = getchar();
between scanf("%d",&x); and ch = getchar();
then your code work correctly.
Because when you take input from user, in this time you press a new line \n after the integer value then the variable ch store this new line by this line of code ch = getchar(); and that's why you program crash because condition can not work correctly.
Because we know that a new line \n is also a char that's why you code crash.
So, for skip this new line \n add one more time ch = getchar();
like,
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
ch = getchar(); // this line store your char input
or
scanf("%d",&x);
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
pieces of code work correctly.
I need to use scanf to get a character and a string which would store the user's answer. (yes/no)
The code below skips scanf("%c", &elem).
while ( !strcmp ("yes", option))
{
printf("enter the elements \n\n");
elem=getchar();
printf("you have entered %c\n",elem);
enqueue(st, elem);
printf("please enter yes or no ");
scanf("%s[^\n]",option);
}
./out
enter the elements
a
you have entered a
enqueue elem= a
please enter yes or no yes
enter the elements
you have entered
enqueue elem=
You don't have any scanf("%c", &elem) in your code... btw the problem is with the enter for scanf. When you get an input by scanf, an enter character stays in the input buffer which will be read by your getchar() function in the second round. one simple way to solve it is to add a dummy getchar after your scanf line:
while ( !strcmp ("yes",option))
{
printf("enter the elements \n\n");
elem=getchar();
printf("you have entered %c\n",elem);
enqueue(st,elem);
printf("please enter yes or no ");
scanf("%s[^\n]",option);
getchar();
}
You can find more information about how to clear your input buffer here: How to clear input buffer in C?
I can recommend you consider two things:
For getting only a character, I personally found it much more easier to use getch and getche function in Windows, and equivalent of them for GCC-compatible environments. You can find samples of it online or on this line [What is Equivalent to getch() & getche() in Linux?
Always flush the input buffer after you read your input to prevent any similar problems to happen.
The input functions check the input buffer, which you can find at 0xb8000000, and check the first input there. If the buffer is empty, they wait for the user to enter the input, otherwise, they check the first element in the buffer and then examine that to what they expect to read. If they succeed, they read it and remove it from buffer. Otherwise, they fail to give you your input and depending on the function, the result is different.
For Example, consider the following line:
scanf("%d %d %f", &a, &b &c);
and give the input as:
a 2 4
The scanf will return 0, which means it reads zero inputs so 'a', 2, and 4 remains in your buffer. So your buffer looks like: [a, 2, 4]. As a result if you add the following line:
scanf("%c", &ch);
scanf will try to get a character from the buffer, and it reads character 'a' and put it in variable ch. So it doesn't get any input from user. And you end up with having 2 and 4 on your buffer again.
When you are pressing Enter/Return key to enter the element then a \n character is also passed to the buffer along with the element. This \n is read by your getchar on next call.
To consume this \n place this line after the getchar();
int ch;
while((ch = getchar()) != EOF && ch != '\n');
Take care mixing scanf() format specifiers "%c", "%s" and "%[]".
Correct usage of "%[^\n]": there is no s. If leading whitespace in not wanted to be saved, include a leading space as in " %[^\n]"
char option[100];
// scanf("%s[^\n]", option);
scanf(" %[^\n]", option);
// or better
scanf(" %99[^\n]", option);
// or pedantic
switch (scanf(" %99[^\n]", option)) {
case EOF: HandleEOForIOError(); break;
case 0: HandleNoData(); break; // might not be possible here.
case 1: HandleSuccess();
Correct usage of "%c". If leading whitespace in not wanted to be save, include a leading space as in " %c". This may be the case in OP's code so the preceding inputs Enter or '\n' is consumed.
char elem;
scanf(" %c", &elem);
Correct usage of "%s". Leading whitespace is not saved with or without a leading space.
char option[100];
scanf("%99s", option);
// Following works the same.
scanf(" %99s", option);
what is the problem here? scanf doesnt seems to working in while loop. i was trying to find out vowel & consonent until user wants.
Here's the code:
#include <stdio.h>
main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%d",&c);
if(c=='n')
printf("thnks\n");
} while(c=='y');
return 0;
}
You are trying to read a character using %d which is wrong. Use %c instead.
Change code to scanf("%c",&c) your original code is getting the y/n entries as digits not characters
Edit:
Probably you are getting the carage return instead of the character try using getc or fgets instead and get the first character.
I think the problem might be here:
scanf("%d",&c);
It should be:
scanf("%c",&c);
Here is the Correct code:
#include <stdio.h>
int main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
getchar(); //to remove the \n from the buffer
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c); //Here you were using %d instead of %c
getchar(); //to remove the \n from the buffer
if(c=='n')
printf("thnks\n");
}while(c=='y');
return 0;
}
Both scanfs should be changed like this:
scanf(" %c",&x);
...
scanf(" %c",&c);
Note the space before the %, it's important: it consumes leading whitespace, which includes the endline characters left over in stdin after processing the input.
Please try with this code to run the loop multiple times.
EDIT: Different solution without fflush(stdin). Please define a string of 8 characters as
char str[8];
and modify the code in the loop as
fgets(str, 8, stdin); // To read the newline character
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c);
fgets(str, 8, stdin); // To read the newline character