The following 2 codes are almost identical, only that the switch statements are slightly different.
The 2nd code has the issue of requiring an additional enter key to be pressed when I enter '3' as input to exit the program.
Any opinions are appreciated =)
Working code :
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void clearKeyboardBuffer() {
int ch;
while ((ch = getchar() != '\n') && (ch != EOF));
}
void rgr1(){
char chArr[BUFSIZ];
char choice;
int choiceint, rating, len;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
len = strlen(chArr);
// converts scanned char to int
choiceint = choice - '0';
if(!isdigit(choice) || len > 2 || choiceint > 3){
printf("You did not enter an accepted digit.\n");
}
else if(choiceint != 3){
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
}// end of switch
clearKeyboardBuffer();
}// end of else if
else{
}// end of else
}// end of do
while(choiceint !=3 || len > 2);
}
Shortened code, but an additional enter key is required to be pressed when I enter '3' to exit the application.
Code:
#include <stdio.h>
#include<ctype.h>
#include <string.h>
void clearKeyboardBuffer() {
int ch;
while ((ch = getchar() != '\n') && (ch != EOF));
}
void rgr2(){
char chArr[BUFSIZ];
char choice;
int choiceint, rating, len;
char *p;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
len = strlen(chArr);
choiceint = choice - '0';
if(!isdigit(choice) || len > 2 || choiceint > 3 ){
printf("You did not enter an accepted digit.\n");
}
else{
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
default:
break;
}// end of switch
clearKeyboardBuffer();
}// end of else
}// end of do
while(choiceint !=3 || len > 2);
}