Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I force user to input a positive integer?

Tags:

c

command-line

Force user to input a positive integer and put user in a loop till they do.

So I want everything including characters not allowed just over > 0

I tried the following:

while (i < 0) do { 
    printf("please input a number that's positive"); 
    scanf("%d", i); 
}
like image 922
Taz B. Avatar asked Dec 26 '22 20:12

Taz B.


1 Answers

For positive integer use the following code

int i;
do 
{ 
  printf("please input a number that's positive"); 
  scanf("%d", &i); 
}while (i < 0); 

The c language provides no error checking for user input. The user is expected to enter the correct data type. For instance, if a user entered a character when an integer value was expected, the program may enter an infinite loop or abort abnormally.

like image 109
Siddiqui Avatar answered Jan 08 '23 04:01

Siddiqui