I wrote this program:
#include <conio.h>
#include <stdio.h>
void main()
{
char ch='a';
while(ch!='y'&&ch!='n')
{
printf("\nDo you want to print the output?(y/n)");
scanf("%c",&ch);
}
if(ch=='y')
printf("\n accepted!");
getch();
}
expected output:
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)y
accepted!
Instead I get:
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)y
accepted!
I don't know that why the sentence"Do you want to print the output?(y/n)" is written twice in output?
Beacuse scanf accepts a \n character and leaves it in the buffer.
To consume that character you can use:
scanf(" %c",&ch);
This should work for you:
(You have to remove all '\n' and put a space before %c)
(Because scanf read's everything to \n and the new line is still in the buffer, so in the next iteration the new line get's read from scanf)
#include <conio.h>
#include <stdio.h>
void main()
{
char ch='a';
while(ch!='y'&&ch!='n')
{
printf("Do you want to print the output?(y/n)");
scanf(" %c",&ch);
}
if(ch=='y')
printf("accepted!");
getch();
}
So you get your output:
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)y
accepted!
Make the scanf in your function like this.
scanf(" %c",&ch);
Reason for making like this. When you are giving an input to that question that time enter will be pressed. So here when the enter is pressed newline character is placed. So scanf get the newline as a character then the loop will continue for the next time. If you give the spaces before the control string it will skip the white line characters from our input, then it ask the input for that.
Problem with the input buffer. However, the solution is very simple:
instead of scanf(" %c",&ch);, use:
do { ch=getchar(); } while(ch=='\n');
Related
So I create this small program to represent my problem. Run program enter 'a' press ENTER.
C Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char o;
while(1)
{
printf("> ");
scanf("%c",&o);
switch(o)
{
case 'a' :
printf("%c\n",o);
break;
case 'q' :
return 0;
}
}
}
Output is:
> a
a
> > *(waiting for input)*
What I expected it to be:
> a
a
> *(waiting for input)*
Please give me some advice how to get my problem solved. Thank you.
There is a \n on stdin after you scan out a. Either call getchar() after you have grabbed the character or change your scanf to scanf("%c%*c", &o). Because of this, the second time your loop looks for input, it will already have the \n waiting, and it will switch on that value, do nothing, and prompt again.
scanf("%c",&o); will read exactly one character, without skipping whitespace. In other words, it will treat newlines, tabs, and space characters as valid inputs.
To skip the whitespace characters, use
scanf(" %c",&o);
^---- note the extra space here
Add getchar() after your scanf.
After you type the input and hit 'Enter', the '\n' gets stored in the input buffer, and the next scanf takes '\n' as the input. Hence, you first need to get rid of the newline character. This can be achieved by using another variable (clr in the code below) to store the newline character. Here's the modification :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char o,clr;
while(1)
{
printf("> ");
scanf("%c",&o);
clr=getchar(); // line added
switch(o)
{
case 'a' :
printf("%c\n",o);
break;
case 'q' :
return 0;
}
}
}
This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.
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
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
It is a statement given in K&R that printf() and putchar() can be interleaved. If it true then why is the following code not giving the required output:-
#include"stdio.h"
void main()
{
char c,d;
printf("Enter the first character\n");
scanf("%c",&c);
printf("%c\n",c);
printf("Enter the second character\n");
d=getchar();
putchar(d);
printf("\n");
}
Whenever I am executing this program, the output is as follows:-
Enter the first character
a
a
Enter the second character
This is the output. This is also happening if I replace printf() by putchar() and scanf() by getchar(). Why is this happpening?
The first scanf leaves in the input buffer the \n resulting from the Return press, so your second getchar() will acquire this \n instead of acquiring another character from the user.
If you want to skip that newline character, you can either instruct the scanf to "eat" it:
scanf("%c\n",&c);
or "eat it" directly with a call to getchar():
scanf("%c",&c);
getchar();
(notice that these are not exactly equivalent, since the second snippet will eat whatever character happens to be in the buffer, while the first one will remove it only if it's a \n)
You can correct your code like this:
#include <stdio.h>
int main() {
char c, d;
printf("Enter the first character\n");
scanf("%c\n", &c); // Ask scanf to read newline and skip
printf("%c\n", c);
printf("Enter the second character\n");
d = getchar();
putchar(d);
printf("\n");
return 0;
}
You are getting two a's because you type one in which is echoed to the console and then you print it out.
flush the stdin before using getchar()..
In turbo, use fflush()..
In gcc, use __fpurge(stdin)..(this is available in <stdio_ext.h> header)..
Flushing the standard input before scanning anything will solve your issue..
Why does following program produce two output message at the same time, without asking for any input from the user???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
The output is followings:
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Terminal input is read line at a time unless you specify otherwise; scanf reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf() or similar to parse those lines.
Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?