Why does the code get the empty data directly in even times? I have no idea what is going on. Thank you very much.
#include
#pragma warnin
Let's say you typed a
followed by Enter.
The first call to getchar()
returns a
but the newline is still left in the input stream. The next call to getchar()
returns the newline without waiting for your input.
There are many ways to take care of this problem. One of the simplest ways is to ignore the rest of the line after the call to getchar()
.
ch = getchar();
// Ignore the rest of the line.
int ignoreChar;
while ( (ignoreChar = getchar()) != '\n' && ignoreChar != EOF );
You can wrap that in a function.
void ignoreLine(FILE* in)
{
int ch;
while ( (ch = fgetc(in)) != '\n' && ch != EOF );
}
and use
ch = getchar();
// Ignore the rest of the line.
ignoreLine(stdin);
If you don't want to change a lot in your code, I suggest just insert another getchar
at the end of for loop to consume '\n':
#include <stdio.h>
#pragma warning(disable : 4996)
void main() {
int f, a = 10, b = 20;
for (int i = 0; i < 5; i++)
{
char ch;
ch = getchar();
printf("ch = %c\n", ch);
switch (ch)
{
case '+': f = a + b; printf("f = %d\n", f); break;
case '−': f = a - b; printf("f = %d\n", f); break;
case '*': f = a * b; printf("f = %d\n", f); break;
case '/': f = a / b; printf("f = %d\n", f); break;
default: printf("invalid operator\n");
}
getchar();
}
}