0

How can I use a single while loop to restrict entry of negative integers to the code. I have previously tried with two while loops each for the two scanf() and works cool. But I am unable to figure our how to combine them into one while loop. I have removed the two while loops I have originally used. I am completely new to this and I need some ideas.

#include <stdio.h>

int main()

{   
    int num, uplimit, a;

    printf("Which multiplication table do you want? ");

    scanf("%d",&num);

    printf("Please enter the upper limit: ");

    scanf("%d",&uplimit);


    printf("\nMultiplication Table for %d\n", num);

    printf("===========================\n\n");


for(a=1;a<=uplimit;++a)

{

    printf( "%d X %d = %d  %s\n", a, num, num*a, (num*a % 2 == 0) ? "*" : " " );

}

{

    printf("\n* indicates even multiple of %d", num);

}

return 0;
}
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
  • 1
    Possible duplicate of [Check if input is integer type in C](http://stackoverflow.com/questions/4072190/check-if-input-is-integer-type-in-c). – BlackDwarf Jul 26 '14 at 14:48
  • If you read e.g. [this `scanf` (and family) reference](http://en.cppreference.com/w/c/io/fscanf) you will see a table of format codes. I'm sure you can find a format which is good for reading non-negative integers. – Some programmer dude Jul 26 '14 at 14:51
  • @JoachimPileborg: You mean %u and %x? They _do_ accept negative input. An input of -1 will give `UINT_MAX`, for example, with no error indicated. – mafso Jul 26 '14 at 16:26

2 Answers2

3
char c;

while (((c = getchar()) != '\n') && (c != EOF));
scanf("%d",&num);
while (num < 0)
{
    printf("You should use positive numbers!");
    while (getchar() != '\n');
    scanf("%d", &num);
}

Inner while makes input buffer to clean if there were some letters in input. Also, it makes sence to move while (((c = getchar()) != '\n') && (c != EOF)); into a function.

Xandrmoro
  • 83
  • 1
  • 7
3

Simply replace your scanfs by this:

while(scanf("%d", &num) != 1 || num < 0)
    while ((c = getchar()) != '\n' && c != EOF);
Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
  • I was going to answer this question. Thought better. You need to eat the crap, i.e. if it not a number the eat the next character. BTW -1 is harsh and I will rectify that – Ed Heal Jul 26 '14 at 14:57
  • Thanks, yeah I did not understand where it came from :) – Valentin Mercier Jul 26 '14 at 14:58
  • when you enter a char rather than a integer it will not be accepted by scanf and thus remains in buffer and next time in loop again scanf will see that char. So you need to clear it somehow – mSatyam Jul 26 '14 at 15:04
  • @mSatyam Thank you for pointing that out, indeed this is very important and I answered a little too fast here. I have now edited my answer. – Valentin Mercier Jul 26 '14 at 15:07
  • yeah sometime i too miss it.no issues – mSatyam Jul 26 '14 at 15:10