1

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?

3
  • In my case it's not breaking up when you enter "g" or any char ... ? Commented Oct 26, 2012 at 20:37
  • @Omkant Because n is not initialised to anything. You are seeing undefined behaviour. See the answer and comments below. Commented Oct 26, 2012 at 20:40
  • stackoverflow.com/a/22236689/3388865 I have posted a solution to your question in the link above. Commented Mar 7, 2014 at 3:28

1 Answer 1

4

Check the return value of scanf which returns the number of successful inputs read:

int rc = scanf("%d",&n);

if (rc==1 && n>0) {
  ...
}

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.

Sign up to request clarification or add additional context in comments.

1 Comment

scanf("%d",&n) won't remove non-integer bytes from the input stream. The OP wants to continue looping until an integer is entered. So you really need to read a single character if the integer input fails and then loop again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.