检查用户输入是否符合格式
check if user input according to the format
我有一个系统,其中用户以 HH:MM 格式(代码如下)输入入住时间和退房时间
//category input here
printf("Check in time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour,&minute);
printf("Check out time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour2,&minute2);
我如何根据格式验证用户输入,以便不会发生此类错误(下面的示例)
//example one
category: 2
Check in time (HH:MM 24H FORMAT): 1
Check out time (HH:MM 24H FORMAT): 3
Driver has to pay:
//example 2
category: 1
Check in time (HH:MM 24H FORMAT): -1
Check out time (HH:MM 24H FORMAT): 0
Driver has to pay:
我试过了
else if (hour >= 24 || hour2 >= 24 || hour < 0 || hour2 < 0){
printf("\nERROR! HOUR SHOULD NOT BE 24 OR EXCEED 24 OR LESS THAN 0\n");
}
除此之外,我不知道如何检查用户是否使用了正确的格式:(
提前感谢您的帮助
考虑使用 fgets()
阅读 行 的用户输入。
然后用 sscanf()
解析输入 字符串 和尾随 "%n"
以记录扫描偏移 - 如果扫描到那么远。
然后进行范围比较。
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
int n = 0;
sscanf(buf, "%d :%d %n", &hour,&minute, &n);
if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 && hour < 24) {
Success(); // OP's custom code here
} else {
Failure(); // OP's custom code here
}
}
允许 "24:00"
与
相比进行更改
if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 &&
(hour*60 + minute <= 24*60)) {
检查 5 个字符和 \n
:
sscanf(buf, "%*1[0-2]%*1[0-9]:%*1[0-5]%*1[0-9]%*[\n]%n", &n);
if (n == 6) {
// partial success, now re-scan with "%d:%d" and check positive ranges.
我有一个系统,其中用户以 HH:MM 格式(代码如下)输入入住时间和退房时间
//category input here
printf("Check in time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour,&minute);
printf("Check out time (HH:MM 24H FORMAT): ");
scanf("%d:%d",&hour2,&minute2);
我如何根据格式验证用户输入,以便不会发生此类错误(下面的示例)
//example one
category: 2
Check in time (HH:MM 24H FORMAT): 1
Check out time (HH:MM 24H FORMAT): 3
Driver has to pay:
//example 2
category: 1
Check in time (HH:MM 24H FORMAT): -1
Check out time (HH:MM 24H FORMAT): 0
Driver has to pay:
我试过了
else if (hour >= 24 || hour2 >= 24 || hour < 0 || hour2 < 0){
printf("\nERROR! HOUR SHOULD NOT BE 24 OR EXCEED 24 OR LESS THAN 0\n");
}
除此之外,我不知道如何检查用户是否使用了正确的格式:(
提前感谢您的帮助
考虑使用 fgets()
阅读 行 的用户输入。
然后用 sscanf()
解析输入 字符串 和尾随 "%n"
以记录扫描偏移 - 如果扫描到那么远。
然后进行范围比较。
char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
int n = 0;
sscanf(buf, "%d :%d %n", &hour,&minute, &n);
if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 && hour < 24) {
Success(); // OP's custom code here
} else {
Failure(); // OP's custom code here
}
}
允许 "24:00"
与
if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 &&
(hour*60 + minute <= 24*60)) {
检查 5 个字符和 \n
:
sscanf(buf, "%*1[0-2]%*1[0-9]:%*1[0-5]%*1[0-9]%*[\n]%n", &n);
if (n == 6) {
// partial success, now re-scan with "%d:%d" and check positive ranges.