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);