C infinite do while loop -


this simple program class prompts user length of or shower in minutes (as positive integer, re-prompting needed) , prints equivalent number of bottles of water (as integer).

it assumes shower uses 1.5 gallons of water per minute (192 oz) , plastic bottle size of 16 oz

my do-while loop rejects negative numbers , 0, however, if input text such "foo" when prompted length of shower in minutes, program runs infinite loop, forever running loop , printing "how long shower(in minutes)?:"

any ideas how refine while condition avoid this?

#include <stdio.h>  int min_to_bottles(int *n);  int main(void) {     int minutes;     int bottles;         {         printf("how long shower(in minutes)?:");         scanf("%i", &minutes);     }     while (minutes < 1);      bottles = min_to_bottles(&minutes);      printf("equivalent of bottles used per shower is: %i\n", bottles);  }  int min_to_bottles(int *n) {     int bottles;     int oz = 192 * *n;     bottles = oz/16;     return bottles; } 

always check return value of scanf():

int result; {     printf("how long shower(in minutes)?:");     result = scanf("%d", &minutes);     if(result != 1)          break; } while (minutes < 1); 

a shorter version (if 1 scan needed):

printf("how long shower(in minutes)?:");  while ((scanf("%d", &minutes) == 1) && (minutes < 1))     ; 

there no need use pointer parameter in int min_to_bottles(int *n);:

#include <stdio.h>  int min_to_bottles(int n) {     return (192 * n) / 16; }  int main(void) {     int minutes = 0;     int bottles = 0;      printf("how long shower(in minutes)?: ");      while ((scanf("%d", &minutes) == 1) && (minutes < 1 || minutes > 100))         printf("enter number between 1 , 100 : ");      // if(minutes == 0) here means invalid data entered.     //    check done before continuing.      bottles = min_to_bottles(minutes);      printf("equivalent of bottles used per shower is: %d\n", bottles);      return 0; } 

initializing minutes 0 avoid calculating bottles undefined value in case scanf() failed (by entering text example).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -