0

One of the requirements of this project is that if the user enters a letter into the calculator, I have to display a message that you can't do that and let them try again. This is my attempt.

int main(void) {
   char r = 't';
   double a;
    
   while (r == 't') {
      printf("enter the number\n");
      if (scanf(" %lf", &a)) {
         r='f';
      } else 
         printf("Invalid entry, try again\n");
   }
  
   printf("a is %lf", a);
}

It works properly for some letters, like n. But for many others, like r, it goes into an infinite loop

Invalid entry, try again enter the number"

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    This is a really short snippet, it should not be hard to format it properly. – Eugene Sh. Nov 08 '21 at 19:43
  • 1
    As Eugene said, you should really use your editor to properly indent your code. Your very strange usage of newlines (or lack thereof), and inconsistent indentation, might really hide some bugs you might otherwise be quick to spot yourself! When sharing code with others, code formatting is not an optional nicety, but a requirement, so that they can quickly read it! – Marcus Müller Nov 08 '21 at 19:45
  • 2
    In addition, the `scanf` check should be `if (scanf(" %lf", &a) == 1)` because `scanf` can also return `EOF` which is a "true" value. – kaylum Nov 08 '21 at 19:46
  • 1
    After an invalid entry, you need to clear the user’s input, commonly by reading characters until the end of the line (until a newline character is read). In any case, edit the question to provide a [mre], including complete code that compiles without any diagnostic messages. Show sample input that reproduces the problem, the output observed from that input (truncated to a finite length; do not paste text from an infinite loop into the question), and the output desired instead. – Eric Postpischil Nov 08 '21 at 19:47

0 Answers0