[Bug] Console Input Loop C Template
A free, portable, fast and simple C/C++ IDE
Brought to you by:
orwelldevcpp
The Console Input Loop C Template does not work properly. Entering a character other than a/q will not produce the invalid input message. I quickly hacked a fix that both maintains the original behavior and keeps it as simplified as possible (for the benefit of new coders). Here it is:
#include <stdio.h> void Foo() { printf("Hello World!\n"); } int main(int argc, char **argv) { char input = 0; printf("Hello! This is a console application.\n"); printf("Press q to quit, press a to execute foo.\n"); while(1) { if(scanf("%c",&input) == 1) { if(input == 'a') { Foo(); } else if(input == 'q') { break; } else if(input != '\n' && input != ' ') { printf("Invalid input! Ignoring...\n"); } } } return 0; }
Alternatively the following solution will also work:
However it is debatable if this one is easier for a novice to understand than my initial submission. However, it would potentially have them reading the scanf() documentation/references/manpage, which is a good thing.
I have updated the input loop projects for both C and C++ to always produce some kind of output when the return key is pressed. For example, the C file now looks like this: