In the following code, I wish to give an option to the user to type ‘e’ to exit the code and see the results, instead of 100 as used in the code presently . But code is unable to run properly with ‘e’ from the terminal since scanf expects an integer, matching with the declared type. If I type in any character instead of an integer, scanf would store it in the variable in some manner. is that manner fixed? if it is fixed can I use that stored value to check if to exit program or not?
#include<stdio.h>
int main(void)
{
int rating[11], x;
for (int a = 0; a <= 11; a++)
rating[a] = 0;
while (1){
printf("key in 100 to see the results\n");
printf("Enter the rating on a scale from 1 to 10 ?");
scanf("%i", &x);
if ((x < 1 || x > 10) && x != 100)
printf("bad entry ! \n");
if (x == 100){
printf("\nRatings..............No of responses\n");
for (int y = 1; y <= 10; y++)
printf("%2i.......................%2i\n", y, rating[y]);
return 0;
}
rating[x]++;
}
}
scanfreturns the number of items successfully read (or -1 on error). So, you could conceivably check to see ifscanfreturns 0, and bail in that case; it would exit the program if anything non-numeric was entered.If you specifically want to check for
'e', the best bet is tofgetsa whole line of input, check for your special cases usingstrcmp, then useatoito get an integer.