[英]Prompting the user after an if statement in C?
I'm new to C and trying to write a simple program. 我是C语言的新手,正在尝试编写一个简单的程序。 I ask the user to enter a month.
我要求用户输入一个月。 I know how to check if it's a valid month, but unsure how to prompt the user to enter another if it ISNT a valid month.
我知道如何检查是否为有效月份,但是不确定ISNT是否为有效月份时如何提示用户输入另一个月份。 Here is what I came up with: EDIT: updated code
这是我想出的:编辑:更新的代码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int mon;
do {
printf("Enter a month(1=Jan, ..., 12=Dec: ");
scanf("%d", &mon);
} while (mon < 1 || mon > 12);
printf("Not a valid month.");
}
But now my while-block is only getting printed if I enter a number between 1-12. 但是现在,只有当我输入1-12之间的数字时,我的while块才会被打印。 If I enter an invalid month I am still prompted to enter another, but the program terminates if I enter a correct number.
如果我输入了无效的月份,仍然会提示我输入另一个月份,但是如果输入正确的数字,程序将终止。
You can use do-while loop as follows: 您可以使用do-while循环,如下所示:
int mon;
do{
printf("Enter a month(1=Jan, ..., 12=Dec): \n");
scanf("%d", &mon);
} while(mon < 1 || mon > 12);
It will continue, if the input is correct and loop again when false input. 如果输入正确,它将继续,并在输入错误时再次循环。
Based on your updated code, you will print the message when the users input is valid. 根据更新的代码,您将在用户输入有效时打印消息。
You probably wanted something like this: 您可能想要这样的东西:
for (;;)//infinite loop (no condition)
{
printf("Enter a month(1=Jan, ..., 12=Dec): ");
scanf("%d", &mon);
if (mon < 12 && mon > 0) // if inside the range (1-12) then break the loop and continue
break;
else // otherwise show the error message and repeat again
printf("Error message \n");
}
scanf()
is not friendly to bad input. scanf()
对错误的输入不友好。 I would suggest using fgets()
and then parse. 我建议使用
fgets()
然后解析。
int main(void) {
int mon;
for (;;) {
char buf[100];
printf("Enter a month(1=Jan, ..., 12=Dec): ");
fflush(stdout);
if (fgets(buf, sizeof buf, stdin) == NULL)
return 1; // no more input
if (sscanf(buf, "%d", &mon) == 1 && mon >= 1 && mon <= 12) {
break; // Success!
}
printf("Not a valid month ");
}
return 0;
}
Additional testing could to used to detect overflow or data after the integer. 可以使用其他测试来检测整数之后的溢出或数据。
If you like kind of oneliners, here it is: 如果您喜欢那种单线,这里是:
while(printf("Enter Month\n") && scanf("%d",&mon) && (mon < 1 || mon > 12));
code: 码:
main()
{
int mon;
while(printf("Enter Month\n") && scanf("%d",&mon) && (mon < 1 || mon > 12));
}
Output: 输出:
$ ./a.out
Enter Month
0
Enter Month
99
Enter Month
98
Enter Month
44
Enter Month
13
Enter Month
12
$
#include<stdio.h>
int main()
{
int month, condition = 0;
do
{
printf("enter month");
scanf("%d", &month);
if (month < 1 || month>12)
condition = 1;
else
condition = 0;
} while (condition == 1);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.