The following code prints the output(ch is not E) twice. Any idea why?
#include<stdio.h>
void main()
{
while ( getchar() != 'E') {
printf("ch is not E\n");
}
}
The following code prints the output(ch is not E) twice. Any idea why?
#include<stdio.h>
void main()
{
while ( getchar() != 'E') {
printf("ch is not E\n");
}
}
Almost certainly because you entered a character that wasn't E
and then hit the ENTER key, which is itself another character, \n
, the newline character.
This is because C usually operates in "cooked" mode, where no keystrokes are delivered to the application until an entire line is ready. You can switch to raw mode where characters are delivered immediately but you then have to manage things like backspaces or line editing yourself. And keep in mind cooked/raw mode is not an intrisic feature of C itself, rather it's part of the underlying enviroment.
Were you to enter abc
, you would see four lines stating it wasn't E
.
getchar() returns the first character in the input buffer, and removes it from the input buffer. But other characters are still in the input buffer (\n in your example).
#include<stdio.h>
void main()
{
char c;
while ((c = getchar()) != '\n' && c!= EOF && c != 'E') {
printf("ch is not E\n");
}
}