重新提示用户,直到他/她输入大于1的正整数 [英] Re-prompting a user until he/she enters a positive integer value greater than 1
问题描述
我正在解决CS50(问题集1),即water.c。它要求用户编写一个程序,提示用户以分钟为单位的淋浴时间(以正整数表示),然后打印等量的水瓶(以整数表示)。
1分钟的淋浴=消耗了12瓶
主要问题:问题是我们必须确保用户输入的分钟数为正数,否则它将继续提示他返回输入/ scanf语句。只要他输入,他输入length <= 0,我就可以使用while(length <= 0)条件重新提示他,但是当他输入一个字符(即abc123)时,我的代码就会继续执行。任何解决方案?
I'm solving CS50 (problemset 1) i.e water.c. It asks user to write a program that prompts the user for the length of his or her shower in minutes (as a positive integer) and then prints the equivalent number of bottles of water (as an integer). 1 min of shower = 12 bottles consumed MAIN PROBLEM: The problem is that we have to ensure that the user inputs a positive number of minutes otherwise it keeps on re-prompting his back to input/scanf statement. As long as he enters he enters length<=0, I can re-prompt him back using while(length<=0) condition but as he enters a character i.e abc123 in input my code keeps on executing. Any solutions??
>
#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;
}
推荐答案
您可以通过阅读来解决首先是一个字符串,然后提取任何数字:
You can solve this by reading a string first, and then extracting any number:
#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;
}
计划会议:
Enter length: 0
Enter length: -1
Enter length: abd3
Enter length: 4
length = 4
至关重要的是,我总是检查 scanf
的返回值,成功转换的项目数。
Crucially, I always check the return value from scanf
, the number of items successfully converted.
这篇关于重新提示用户,直到他/她输入大于1的正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!