我试图运行此程序,直到用户想要但无法执行。
我尝试使用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');
}
最佳答案
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的命令的风险记住空字符。
关于c - 我想循环这段代码,直到用户想要,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55495511/