读取时间为c中的字符数组

时间:2016-08-01 15:42:05

标签: c arrays

我是C字符数组的新手。我知道要读取字符数组,我们需要使用%s格式说明符使用scanf或gets。

我正在读取时间,因为C中的两个字符数组为h [2]和m [2],其中h表示小时,m表示分钟。

char h[2],m[2];
scanf("%s:%s",h,m);

printf("%s:%s",h,m);

但是当我将11:30作为输入时,它会将时间打印为11:30::30作为输出。谁能说出我的原因?

谢谢。

2 个答案:

答案 0 :(得分:2)

你忘了做一些事情:

  • 您的字符数组需要以null结尾。创建大小为3而不是2的hm,允许将空字符'\0'放在字符串后面。 scanf为您做到这一点。

  • 您可以使用scanf限制输入字符串的大小。 scanf("%2s", h)会将stdin中包含2个字符的字符串放入h

  • 您还可以从第一个字符串中排除:字符:scanf("%[^:]:%s", h, m)

将所有这些放在一起,我们得到:

char h[3], m[3]; // Create two character arrays of 3 characters.
if (scanf("%2[^:]:%2s", h, m) == 2) { // Read the time given and check that two items were read (as suggested by chux)
    printf("%s:%s", h, m); // Print the time given.
}

答案 1 :(得分:0)

尝试这两个选项,我希望他们能满足你:

1 -

char h[3], m[3];

printf("Input time\n");


scanf("%s%s", &h, &m);
printf("\n%s:%s\n", h, m);

return 0;

2 -

int i;
char ch, hour[6];

printf("Input time\nex. HH:MM\n");


while(ch!='\n')
{
    ch=getchar();
    hour[i]=ch;
    i++;
}

hour[i]='\0';
printf("\n");
printf("Time: %s\n", hour);
return 0;