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;
}
If you don't care about Inputs like
1f
then the Above Answers are ok For you, but if you do not want to accept this kind of Input, then the following approach does something like that:Output:
You don't need the first prompt outside the loop because you have already initialised length to zero, so the loop will prompt at least once.
On most platforms other then Wndows, you need to flush stdout to show text not terminated with a newline.
scanf
will return so long as a newline character is buffered and%d
alone will not consume the newline, so you need to ensure that any remaining characters up to and including the newline are flushed to prevent an endless loop.It is good practice to check the return value from
scanf()
since it makes no guaranteed about not modifying its arguments even when a conversion fails.It is not clear why
min
is a variable here sine it is initialised but never re-assigned, but presumably that may be the case in the final program?You can solve this by reading a string first, and then extracting any number:
Program session:
Crucially, I always check the return value from
scanf
, the number of items successfully converted.