gpt4 book ai didi

c - 如何在 C 中检查特定的字符串格式

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:38 24 4
gpt4 key购买 nike

我正在编写一个程序,它以小时:分钟的格式接收时间,因此示例输入为 1:56 或 0:12。

有没有一种方法可以专门检查以确保以该格式输入?还有我可以使用的空终止符是什么?我习惯使用 python,所以 C 真的让我很困惑。谢谢!

#include <stdio.h>

int main()
{
int hour=0, minute=0, total=0;
while (hour != -1)
{
printf ("Enter dive times in the format of HH:MM (hours:minutes), Enter -1 to stop\n");
scanf("%d:%d",&hour, &minute);
if ((hour < -1) || (minute < 0))
{
printf("Invalid input");
}
else
{
printf ("total: %d hour: %d minute: %d", total, hour*60, minute);
total = total + (hour*60) + minute;
}
}
printf("The total is %d The hours is %d The minutes is %d\n",total, (total/60), (total%60) );
printf("The total divetime is %d:%d", total/60, total%60);

最佳答案

Is there a way to specifically check to make sure the input in that format?

  1. 将用户输入的读取为字符串:

    char buf[100];
    if (fgets(buf, sizeof buf, stdin) == NULL) {
    Handle_EndOfFile_or_InputError();
    }
  2. 扫描字符串。寻找一个 int : int。同时扫描不应该存在的附加文本。 (哨兵)

    char sentinel;
    if (sscanf(buf, "%d :%d %c", hour, minute, &sentinel) != 2) {
    Handle_InputIsNot2int();
    }
  3. 检查范围

    #define HOUR_MIN 0
    #define HOUR_MAX 23
    #define MINUTE_MIN 0
    #define MINUTE_MAX 59
    if (hour<HOUR_MIN || hour>HOUR_MAX || minute<MINUTE_MIN || minute>MINUTE_MAX) {
    Handle_InputOutOfRange();
    }
  4. 哦,快乐的一天!根据需要使用小时,分钟

    total += (hour*60) + minute;

关于c - 如何在 C 中检查特定的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com