RaulT RaulT - 1 year ago 80
C Question

How do I make the console keep prompting the user for input until the user enters a positive integer in C?

#include <stdio.h>
#include <cs50.h>

int main(void)
printf("Give me the length of your shower in minutes: \n");
int x = GetInt();
int b = x*12;

if (x <= 0)
printf("Please give me a valid input.\n");

printf("In %i minutes you consumed %i bottles of water!\n", x, b);

This is my code for an algorithm that takes minutes of a shower and converts it to bottles of water used.

I've tried to write it in different ways and even using "scanf" but nothing has worked. The code works fine except that when the user inputs something that is zero or a negative number it just prints "That is not a positive integer." before the program just shuts down. I need it loop back and get another input from the user until they return something positive. I've tried a couple do/while and for loops but I don't think I'm doing it right. Could someone please help a rookie coder out?

Answer Source

The following will simply repeat the prompt until a valid value is entered, then print he result:

int main(void)
    int x = 0 ;

        printf( "Give me the length of your shower in minutes:\n" ) ;
        x = GetInt() ;

    } while( x <= 0 ) ;

    int b = x * 12 ;
    printf( "In %i minutes you consumed %i bottles of water!\n", x, b ) ;

    return 0 ;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download