I am learning c and understand that this language is low-level and in this context lacks exception handling.
I made a simple program where the user choose among some alternatives from a menu. Its just that simple!
The program is divided into a few methods - one of the methods waits for the user to press a key - an integer is expected. Then return this integer to another method which holds a switch-structure.
The problem arises when a character is pressed - in most cases an infinite loop of the else-block is started.
You must choose an alternative 0 - 2. Please try again :-)
You must choose an alternative 0 - 2. Please try again :-)
You must choose an alternative 0 - 2. Please try again :-)
...... and so on
I do not actually know how to solve this. I have tried to use the return value from the scanf-function without success. I have also tried to pass a character (instead of integer) as an argument to the scanf-function - also without success.
Any suggestion how to handle this problem?
#include <stdio.h>
#include <stdlib.h>
void menu();
void runSelection(int selection);
int getSelection();
int pause();
int main(void) {
do{
menu();
runSelection(getSelection());
}while(pause());
return 0;
}
int pause() {
int c;
printf("\n\nPress enter to continue!");
fflush(stdout);
/* flush inputstream */
while((c = getchar()) != '\n' && c != EOF);
getchar();
return 1;
}
void menu() {
puts(" * * * * * * M E N U * * * * * * *");
puts("1. Do something 1");
puts("2. Do something 2");
puts("3. Do something 3");
fflush(stdout);
}
void runSelection(int selection) {
switch (selection) {
case 0:
puts("you pressed 0");
break;
case 1:
puts("you pressed 1");
break;
case 2:
puts("you pressed 2");
break;
}
}
int getSelection() {
int key;
int true = 0;
do {
scanf("%d", &key);
if (key >= 0 && key <=2) {
true = 1;
}
else {
puts("You must choose an alternative 0 - 2. Please try again :-)");
fflush(stdout);
}
} while (true == 0);
return key;
}