-1

I am trying to run this program until user wants but unable to.

I have tried using do-while loop but couldn't achieve the desired output

float water_level;
char command;

do{
    printf("Enter the water level sensor readout in meters : \n");
    scanf("%f",&water_level);

    printf("The water level is: %f \n",water_level);

    if(water_level <= 0.5)
    {
        printf("The output valve is turned OFF \n");
    }
    else
         printf("The output valve is turned ON \n");

    if(water_level < 3.0)
        {
           printf("The water pump is turned ON \n");
        }
    else
        printf("The water pump is turned OFF \n");

    printf("Do you want to run the program Again? \n Type y or n \n");
    command = scanf("%c",&command);

    } while(command == 'y');

}

1 Answers1

2

scanf("%c",&command); returns 1 if you read a character, 0 on end of file, so it cannot be 'y'

warning also with the newline you will read doing char by char (without a space before the %c in the format)

you can do :

char command[4];

do{
    ...
    printf("Do you want to run the program Again? \n Type y or n \n");
    if (scanf("%3s",command) != 1) {
      /* EOF */
      break;
    } 
} while(*command == 'y');

As you can see in the scanf I limit the length of the read string to 3 (allowing yes/no in case ;-) ), that allows to not take the risk to write out of command having size 3+1 to be able to memorize the null char.

bruno
  • 32,421
  • 7
  • 25
  • 37