我想循环这段代码,直到用户想要

时间:2019-04-03 12:42:50

标签: c

我正在尝试运行此程序,直到用户想要但无法执行为止。

我尝试使用do-while循环,但无法实现所需的输出

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 个答案:

答案 0 :(得分:2)

scanf("%c",&command);如果读取一个字符,则返回1,在文件末尾返回0,因此它不能为'y'

还使用换行符警告您将逐个字符读取(格式为%c 前没有空格)

您可以:

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');

正如您在 scanf 中所看到的,我将读取字符串的长度限制为3(如果是,则为yes / no ;-)),这样就不会冒着写出的风险。大小为3 + 1的 command 可以记住空字符。