I'm taking a user-inputted single character. The program continues getting characters with getchar until it encounters a non-space character, then uses that character to print a display.
If the user enters control-D instead of a character, the getchar input terminates and the program should too.
char border;
printf("Enter the character for the border: ");
while ((border = getchar()) != EOF && border != '\n') {
if (!isspace(border)){
break;
}
}
Except if I enter control-D, the loop terminates...and the program allots the garbage character ▒▒ to border, then continues the program.
I've tried if (!border) { return 1; }
and attempting to return 1 if border compared to ▒▒ is true, but no dice either way.
What's going on, and how can I handle this?
Pressing CTRL+D doesn't terminate the program. Instead, it closes the stdin input stream. Most command-line utilities are designed to do something and then terminate after this happens. Contrast this with CTRL+C, which sends a kill signal to the program.
Your code currently works by assigning the return value of
getchar()
toborder
, so if getchar returns EOF, it will assign EOF to border, then exit the loop. You can test for whether this happened by checking if border is equal toEOF
after the loop.As @Olaf pointed out, there's another issue here. Notice that
border
is achar
and thatgetchar
returns an integer. Change the type ofborder
toint
to prevent issues later on in your code.Hope this helps!