Infinite loop, program ignoring lines

Viewed 52

I need a little help im sort of new to C programming. I'm having some trouble, for some reason the program won't read the line that im trying to take choice as input from the user which is causing me to have infinite loop neither the menu is printing.

Also stuff like this happen with me a lot of the time like when I copy my friends' code how it is it dosent run any loops even my teacher doesn't know why so if you can help in this too please do .

    #include <stdio.h> 
    #include <stdlib.h> 
    #include <time.h> 
    #include <string.h>

    int main (){
      int choice ,score=0; 
      char name [30]; 

      puts("Welcome to our game , Have fun !\n ");
      puts("Enter your name");
      scanf("%c",name);

      printf("1-Start new game\t2-show recorde\n3-Help         \t4-Show score\n5-Reset score   \t6-Quit game");
      scanf("%d",choice);

      while(choice!=6){

        switch(choice){
        case 1 : 
          break;
        case 2 : 
          break;
        case 3 : 
          break;
        case 4 :
          break;
        default :
          puts("\n invalid input ");
          break;
        }//end switch
      }//end while loop
   }//end main
1 Answers

Your usage of scanfis wrong.

scanf("%c",name);

Format specifier %c is not suitable to read a string. It only reads 1 single character. The other members of name array will be untouched and as local variables are not initialized to 0, that is not a valid nul-terminated string.

As soon as you try to print name or perform any string operations with it, this will result in undefined behaviour.

As a result, whatever you type after first character, stays in input buffer and is fetched during next read attempt.

To fix this, use format specifier %s.

When you now try to read the choice as an integer

scanf("%d",choice);

the input buffer contains remaining letters and also \n from first call, which does not match any number. After the call choice is not modified and still contains its indetermined content (You don't initialize it)

You should always check return value of scanf to see how many parameters were read. It would show you that it didn't find any value.

Besides that, you also provide invalid parameter. You must provide the address of an integer. This is undefined behaviour.

This is the reason why you always enable warnings in your compiler. It should warn you about this error.

To fix this, use

int ret = scanf(" %d", &choice);
if (ret != 1)
  // error handling, try again, etc.

Note the space in the format string to skip whitespace including \n.

Finally, you enter your loop with a "random" value in choice and never try to read again. How would you expect to leave the loop without this?

If your teacher really doesn't know why, the missing indentation might be a reason.

Related