0

This Code does what it should do, as long as you really type an integer, as it asks you in line 10, but if you type a letter of something that isn't an integer it just prints out the lines 10 and 14 over and over and I really don't understand why, shouldn't it check the conditions for the while loop before it executes it another time?

1  #include <stdio.h>
2  #include <stdlib.h>
3  #include <time.h>
4 
5  int raten(int zuErraten){
6      int geraten = 0, check = 1, versuche = 0;
7      while (versuche < 100 || geraten != zuErraten) {
8          versuche++;
9          printf("%i\n", versuche);
10         printf("Gib eine Zahl zwischen 1 und 100 ein:\n");
11         check = scanf("%i", &geraten);
12 
13         if (check == 0) {
14             printf("Gib lediglich eine Zahl ein und drücke Enter:\n");
15             check = 1;
16             geraten = 0;
17             continue;
18         }
19 
20         if (geraten < 1 || geraten > 100){
21             printf("Die Zahl sollte wirklich zwischen 1 und 100 sein, wobei 1 und 100 auch erlaubt sind!\n");
22             continue;
23         }   
24 
25         if (geraten < zuErraten) {
26             printf("Du hast %i geraten, diese Zahl ist leider zu klein!\n", geraten);
27         }
28         
29         if (geraten > zuErraten) {
30             printf("Du hast %i geraten, diese Zahl ist leider zu groß!\n", geraten);
31         }
32         
33     } 
34     
35     return versuche;
36 }
37 
38 int main (int argc, char **argv){
39     time_t t; 
40     srand((unsigned) time(&t));
41     int zuErraten, geraten, versuche;
42 
43     zuErraten = (rand()%100) + 1;
44     printf("%i\n", zuErraten);
45     versuche = raten(zuErraten);
46     printf("Herrzlichen Glückwunsch, du hast die Zahl erraten.\nDu hast dafür %i Versuche gebraucht!\n", versuche);
47 }
Julian
  • 19
  • 4

1 Answers1

0

It's because scanf doesn't remove whatever is in the input buffer if it doesn't match the format. So the next iteration it will read exactly the same input again, and fail. And again, and again...

I suggest you use e.g. fgets to read the input, and then use sscanf to parse it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621