Currently, I have a loop in my program that has the format:
#include<stdio.h>
int main()
{
int n;
while(1)
{
printf("Enter a positive number, n");
scanf("%d",&n);
if(n>0)
{
break;
}
}
}
My intention in using the if(n>0) statement was to exit the loop if and only if the user enters a positive integer. However, if the user types in the character “g”, for example, the loop will still break, as the ASCII value will be interpreted. How do I form this loop so that it breaks just when the user enters a positive integer value for n?
Check the return value of scanf which returns the number of successful inputs read:
I would suggest you to use fgets to read the input into a string and convert into integer using strtol as scanf is a poor choice for the reason said by @paddy.