Scanf function causing infinite loop

Asked

Viewed 298 times

0

I have a simple code that converts a char in a int within a loop while, but when I execute and place the first char, the program goes into loop infinite, here comes 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;
}
  • is not the scanf that cause infinite loop, is itself while. With while(1) how will it exit the loop? 1 will never cease to be 1

1 answer

1

The code has no stopping condition. From what I understand, you want to leave the loop when the user type 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 being displayed the error message, you use the command break, which closes the loop and "follows the flow", to end the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.