details in the reply..
Printable View
details in the reply..
Hi all!
I cannot figure out why the output prints the printf line twice.. in this program.. thanks..
here is the code with the output:
Code:#include<stdio.h>
main()
{
char ch;
while (ch!='0')
{
printf("enter a char other than 0\n");
ch=getchar();
}
}
enter a char other than 0
d
enter a char other than 0
enter a char other than 0
What happens after you press the d key?
Quzah.
well, it prints "enter a char other than 0" twice...
what is the solution to this problem?
ok teacher, what is the right way to deal with this then?
It really depends on what the specs of the program are. If the specs are something like "print a prompt and read a character; if the character is not '0', then repeat" then we will say it for the fourth time in this thread: there is no error in your code and therefore there is nothing to fix. If the specs are something other than that, then you need to tell us what they are.
allright, my bad, the spec follows-
write a program, which allows users to enter characters until the input is '0'.
Without using system specific functions (kbdhit, getch), you can't do what your program specs, as written in your last post, request. There's nothing keeping you from entering: "1230321" and hitting enter. So unless you read keystrokes - not characters - you can't do what you want.
Quzah.
well, thanks for all the help guys...
Your program fits the requirement as given by you, if you change the wording slightly. It will allow you to enter characters, and it will stop the loop when it hits '0'.
All the rest has to do with buffering, and the way input is actually typed versus how it is being handled.
Quzah.
- You prompt for input.
- You press 'd' followed by the "Enter" key -> the buffer contains two characters 'd', '/n'.
- getchar reads 'd' from the buffer -> buffer contains single character '/n'.
- Since 'd' is not '0' you reprompt for input, but the buffer already contains '/n' and program doesn't wait for you to input anything.
- getchar reads '/n' from the buffer -> buffer is now empty.
- Since '/n' is not '0' you reprompt for input, program waits for user input.
The double print happens because of the green bits above.