I've been working on the code below for a little whlie, and I've almost got it done good, but there is still one thing nagging me. As the code stands now, if the user
hits a number > 3 or a letter, it works fine. But if they just hit "enter", they have to hit it twice in order for the corresponding error message to display. It's not a big deal,
but I'd like to know why that is and if there is any way to fix that. My theory is that since you have to hit enter to terminate fgets, if you just hit enter, it reads in \n,
and requires another enter to terminate, that's the only thing I can think of....
Code:
#include <stdio.h>
#include <stdlib.h>
void cls() {
printf("\x1b[2J");
}
void cb() {
int cb;
while ((cb = getchar()) != '\n');
return;
}
void intro();
void menu();
int main() {
printf("\x1b[0m");
printf("\x1b[42m");
cls();
intro();
menu();
return 0;
}
void intro() {
cls();
printf("\x1b[31m");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" Welcome to Smith Sayings - Freeware Edition\n");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("\x1b[34m");
printf(" Press <ENTER> to continue...\n");
getchar();
printf("\x1b[0m");
return;
}
void menu() {
int choice;
char ui[2]; //ui = user input
cls();
printf("\x1b[34m");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" ***********Main Menu********** ");
printf(" * * ");
printf(" *\x1b[31m 1)\x1b[34mRun Story * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" *\x1b[31m 2)\x1b[34mAbout * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" * * ");
printf(" *\x1b[31m 3)\x1b[34mExit * ");
printf(" * * ");
printf(" ****************************** ");
printf("\n\n\n\n");
printf(" Choice:");
fgets(ui,2,stdin);
cb();
if (sscanf(ui,"%d",&choice) != 1) {
cls();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" Please enter a valid selection\n");
printf("\n Press <ENTER>\n");
getchar();
menu();
}
if (choice == 1) {
printf("Choice 1 selected");
getchar();
exit(0);
}
if (choice == 2) {
cls();
printf("\x1b[32m");
printf("\x1b[34m\n\n\n\n\n\n\n\n\n\n\n\n\n%25sSmith Sayings Freeware Version\n","");
printf("\n%25sCreated by \x1b[32mAsh Smith\x1b[34m\n","");
printf("\n%25sEmail:\x1b[[email protected]\x1b[34m\n","");
printf("\n\n\n\n%25sPress <ENTER> to return to the main menu\n","");
getchar();
menu();
}
if (choice == 3) {
printf("Exit selected");
getchar();
exit(0);
}
else {
cls();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf(" Please enter a number between 1 and 3\n");
printf("\n Press <ENTER>");
getchar();
menu();
}
return;
}