Scanf function causing infinite loop

0

I have a simple code that converts a char into an loop while , but when I run and put the first char , the program goes into loop infinity, here goes the code:

#include <stdio.h>
int main()
{
   char c;

   while (1)
   {
       printf("Enter a character: ");
       if (scanf("%c", &c) == 0)
           printf("Err");

       printf("The numeric form of %c is %d\n", c, c);
   }

   return 0;
}
    
asked by anonymous 30.04.2018 / 18:11

1 answer

0

The code has no stop condition. I understand that you want to exit the loop when the user types 0 .

while (1)
{
   printf("Enter a character: ");
   if (scanf("%c", &c) == 0) {
       printf("Err");
       break;
   }

   printf("The numeric form of %c is %d\n", c, c);
}

A simple alternative to this is, after you display the error message , you use the and the flow to terminate the application.

    
30.04.2018 / 18:21