So my question is the following.
int n=0;
while(n<=0)
scanf("%d",&n);
This code enters in an infinite loop, and I don't have a clue why. When the user inputs a number > 0, the loop was supposed to stop.
And thanks:)
So my question is the following.
int n=0;
while(n<=0)
scanf("%d",&n);
This code enters in an infinite loop, and I don't have a clue why. When the user inputs a number > 0, the loop was supposed to stop.
And thanks:)
Over and over and over and over...
stdin
is (generally) line-buffered - one has to press <enter>
to make the terminal transfer the characters to your program. So now there's a dangling newline character in the buffer, and scanf()
will try to read it during the next iteration, but it's not an integer, so it fails and doesn't change the contents of the variable. To solve this, make scanf()
eat the newline:
scanf("%d\n", &number);
(Oh yes, n
is also used uninitialized, but it seems that your code enters the loop anyway, so that's not the issue. Do initialize it, though, else you will face other strange errors.)
while (n <= 0)
// something
means "do something while value of n
is less or equal to 0
". Just make sure that n
is initialized when condition n <= 0
is being evaluated. Using uninitialized variables produces undefined behavior.
You should do:
int n = 0;
while (n <= 0)
scanf("%d\n",&n);
Since you claim to have tried things and they didn't work (although I don't see why) let's try something else. Let's use a programmer's best friend: printf
. How about trying to run this code instead:
int n = 0;
while(n <= 0)
{
printf("Please enter a number: ");
scanf("%d\n", &n);
printf("I see you entered: %d\n", n);
}
printf("Done with the loop. The value of n is: %d\n", n);
This will let you see what the computer is doing and what values it reads as it reads them. Try replacing your code with the above and let's see what happens.
I think you should change your compiler because i'm getting the fine result.
You might have a problem somewhere else.
You can check here.:
Code:
#include<stdio.h>
main( )
{
int n = 0;
while (n <= 0)
scanf("%d",&n);
printf("%d",n);
}
Input:
-5
4
Output:
4