Hamza Azam Hamza Azam - 4 months ago 52
C Question

Re-prompting a user until he/she enters a positive integer value greater than 1

I'm solving CS50 (problemset 1) i.e water.c. It asks user to write a program that prompts the user for the length of his or her shower in minutes (as a positive integer) and then prints the equivalent number of bottles of water (as an integer).
1 min of shower = 12 bottles consumed
MAIN PROBLEM: The problem is that we have to ensure that the user inputs a positive number of minutes otherwise it keeps on re-prompting his back to input/scanf statement. As long as he enters he enters length<=0, I can re-prompt him back using while(length<=0) condition but as he enters a character i.e abc123 in input my code keeps on executing. Any solutions??


#include <stdio.h>
int main()
{ int length=0;
int min=12;
int bottle=0;
printf("Enter length of his or her shower in minutes");
scanf("%d", &length);
while (length <= 0){
printf("Enter length of his or her shower in minutes");
scanf("%d", &length);
bottle= (min*length);
printf("%d", bottle);

return 0;


You can solve this by reading a string first, and then extracting any number:

#include <stdio.h>

int main(void)
    int length = 0;
    char input[100];
    while(length <= 0) {
        printf("Enter length: ");
        if(fgets(input, sizeof input, stdin) != NULL) {
            if(sscanf(input, "%d", &length) != 1) {
                length = 0;

    printf("length = %d\n", length);
    return 0;

Program session:

Enter length: 0
Enter length: -1
Enter length: abd3
Enter length: 4
length = 4

Crucially, I always check the return value from scanf, the number of items successfully converted.