我是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
作为输出。谁能说出我的原因?
谢谢。
答案 0 :(得分:2)
你忘了做一些事情:
您的字符数组需要以null结尾。创建大小为3而不是2的h
和m
,允许将空字符'\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;