1

Have the code below which is producing an infinite loop. It's checking to see if the user gave an integer for the input, and if not then it should perform another loop iteration to ask again. What's occurring is it prompts the user, and if the user doesn't input an integer then the loop runs indefinitely without asking the user again for a new integer. I would EXPECT it to, but that's not what it's doing.

   int arrowBaseHeight = 0;
   int arrowBaseWidth = 0;
   int arrowHeadWidth = 0;
   int rc = 0; //Return code of user input
   
   do {

      printf("Enter arrow base height greater than 1:\n");
      rc = scanf("%d", &arrowBaseHeight);

   } while (arrowBaseHeight < 1 || rc == 0);

Why is it doing this, and anyone know a way to fix it?

Thank you all so much.

GainzNerd
  • 312
  • 1
  • 10
  • 2
    If `scanf` fails to parse the input, it will leave it in the input buffer. Therefore it's often recommended to [read whole lines](https://en.cppreference.com/w/c/io/fgets) and then use `sscanf` to parse. – Some programmer dude Sep 28 '20 at 22:18

1 Answers1

0

You have not written any code to read the non-integer. So every time you try to read an integer, you fail. If you want to read a line of input from the user and parse it to see if it's a valid integer, write code that reads a line of input.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Seems like I have by setting rc = scanf("%d", &arrowBaseHeight); This is how my instructor asked us to check for the return code of scanf. If it doesn't match an input value, rc would remain 0. I expect scanf to ask on each iteration. – GainzNerd Sep 28 '20 at 22:23
  • @kvnr The `scanf` function doesn't "ask" anything. It just tries to read an integer and reports whether it was able to. If it isn't able to read an integer, it doesn't read a non-integer. You have no code to read anything but an integer, so if a non-integer is entered, no code of yours will ever read it in. – David Schwartz Sep 28 '20 at 22:25