为什么用户输入数据中所需的数字没有存储在C中

问题描述 投票:0回答:1

我的目标是使用

scanf()
函数的属性。我想抑制输入中的
':'
,以将小时和分钟值放入各自的变量
hours_var
minutes_var

#include<stdio.h>
#include<string.h>
void main()
{
    int hours_var,minutes_var;
    printf("Whats the time??\n");
    scanf("%d*c%d",&hours_var,&minutes_var);
    printf("%d\n", hours_var);
    printf("%d\n",minutes_var);
}

输出:

Whats the time??
2:24
2
0

我想要 24 在

minutes_var
变量中。我错过了什么??

c scanf
1个回答
0
投票

正如@mch解释,您在

%
之前缺少指定字符
*c
的格式。完整的格式字符串应为
"%d%*c%d"

请注意,这将匹配(并丢弃)前面的 %d 说明符未使用的

任何
字符,因此诸如
2t24
之类的输入格式将起作用。您可以显式匹配
:
字符,如
%d:%d

正如@一些程序员家伙指出的那样,应始终检查

scanf
的返回值,以确保在发生少量转换时,您不会使用不确定的值。

#include <stdio.h>

int main(void)
{
    int hours, minutes;

    printf("What is the time: ");

    if (2 != scanf("%d:%d", &hours, &minutes)) {
        fputs("Invalid format.\n", stderr);
        return 1;
    }

    printf("%d\n%d\n", hours, minutes);
}
What is the time: 2:24
2
24
What is the time: 2t24
Invalid format.

您还可以考虑使用

fgets
读取整行,并使用
sscanf
或使用 POSIX
strptime
等函数解析日期和时间格式。

© www.soinside.com 2019 - 2024. All rights reserved.