Ham*_*zam -2 c validation input cs50
我正在解决CS50(问题集1)即water.c.它要求用户编写一个程序,在几分钟内(以正整数形式)提示用户他或她的淋浴长度,然后打印相同数量的水瓶(作为整数).淋浴1分钟=消耗12瓶主要问题:问题是我们必须确保用户输入正数分钟,否则它会继续重新提示他返回输入/扫描声明.只要他进入,他输入长度<= 0,我可以使用while(长度<= 0)条件重新提示他,但当他输入一个字符,即输入中的abc123时,我的代码继续执行.有解决方案??
>
#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;
}
Run Code Online (Sandbox Code Playgroud)
你可以先读取一个字符串,然后解压缩任何数字来解决这个问题:
#include <stdio.h>
int main(void)
{
int length = 0;
char input[100];
while(length <= 0) {
printf("Enter length: ");
fflush(stdout);
if(fgets(input, sizeof input, stdin) != NULL) {
if(sscanf(input, "%d", &length) != 1) {
length = 0;
}
}
}
printf("length = %d\n", length);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
计划会议:
Enter length: 0
Enter length: -1
Enter length: abd3
Enter length: 4
length = 4
Run Code Online (Sandbox Code Playgroud)
至关重要的是,我总是检查scanf成功转换的项目的返回值.