简体   繁体   English

检查用户输入是否按照格式

[英]check if user input according to the format

I have a system where the user key in the check in time and check out time in a HH:MM format (code below)我有一个系统,其中用户以 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);

how can i validate the user input according to the format so that such error wont happen (example below)我如何根据格式验证用户输入,以免发生此类错误(以下示例)

//example one
category: 2
Check in time (HH:MM 24H FORMAT): 1
Check out time (HH:MM 24H FORMAT): 3

Driver has to pay: $2

//example 2
category: 1
Check in time (HH:MM 24H FORMAT): -1
Check out time (HH:MM 24H FORMAT): 0

Driver has to pay: $1

i've tried我试过了

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");
}

other than that, i have no idea or solution on how to check whether the user is using the correct format :(除此之外,我不知道如何检查用户是否使用正确的格式或解决方案:(

thanks in advance for the help在此先感谢您的帮助

Consider reading a line of user input with fgets() .考虑使用fgets()读取一行用户输入。

Then parse the input string with sscanf() with a trailing "%n" to record scanning offset - if scanning went that far.然后使用带有尾随"%n" sscanf()解析输入字符串以记录扫描偏移量 - 如果扫描进行了那么远。

Then followup with range comparisons.然后进行范围比较。

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 
  }
}

To allow "24:00" change compare to允许"24:00"更改比较

  if (n > 0 && minute >= 0 && minute < 60 && hour >= 0 && 
      (hour*60 + minute <= 24*60)) {

To check for exactly 5 characters and \\n :要检查正好 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM