1

I am writing a code for university. We should use enum and switch case. The user gives a number from 1-7. The result is {doe=1, re, mi, sol, fa, la, si, default= different number}.

However, I thought the default should come every time something different from 1-7 appears, but when the user types any letter or text, the program starts an infinite loop. How can I correct that?

I have tried the !isdigit(), but I still have the same problem.

Below you can see the code:

#include <stdio.h>
#include <ctype.h>
int main (){
enum tast{doe = 1, re, mi, fa, sol, la, si}taste;
int opt;

 do{
    printf("Geben Sie ein Zahl zwischen 1 und 7 ein: ");
    fflush(stdout);
    scanf("%u", &taste);

    /*
     *
     *   if(!isdigit(taste)){
     goto exit_loop;
    }
    exit_loop:
     *
     */

   switch(taste){
   case doe:
        printf("doe");
        break;
   case re:
        printf("re");
        break;
   case mi:
        printf("mi");
        break;
   case fa:
        printf("fa");
        break;
   case sol:
        printf("sol");
        break;
    case la:
        printf("la");
        break;
    case si:
        printf("si");
        break;
    default:
        printf("--");
        break;
    }

printf("\n\nPressen Sie '0', um das Programm zu schliessen: ");
    fflush(stdout);
    scanf("%d", &opt);

    printf("\n");

    }while( opt!=0);

    return 0;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bruno
  • 19
  • 1
  • 2
    That is because the letter is not processed and remains in the input buffer, so next time it is still not processed. Consider obtaining input with `fgets` into a string and apply `sscanf` to that string. if it fails, input another string. – Weather Vane Mar 21 '20 at 19:19
  • 1
    Rather than `re, mi, sol, fa, la, si`, I would expect `re, mi, fa, sol, la, si` – chux - Reinstate Monica Mar 21 '20 at 19:30
  • @hanie that is horrible: the more you try to hedge around the way scanf works, the worse it gets. – Weather Vane Mar 21 '20 at 19:52
  • @WeatherVane I know it's strange ,but it works, yet I think you're right and I don't why it works? – hanie Mar 21 '20 at 19:53
  • When i tried something like {sscanf(taste,"%u", 100);} it asks for a breakpoint. However after reading a little bit more abount fgets and sscanf I came across with "getchar()". If I write it below the {scanf function} the problem is gone. – bruno Mar 22 '20 at 21:25

0 Answers0