【发布时间】:2014-08-29 12:14:55
【问题描述】:
我正在尝试构建一个程序,让用户以这种格式“01'14'2013”输入日期,并将其输出为这种格式“2013 年 1 月 14 日”。我正在尝试将保存用户输入的字符串复制到另一个字符串上,以便稍后将其连接到原始字符串上,而无需字符串的第一个和第二个索引,这样我就只有 '/14/2013',来自原始字符串,然后将 '/' 替换为 ' ' 以便读取月份、日期和年份....但是由于某种原因,当我尝试将原始字符串从输入复制到另一个字符串(我打算稍后连接),它不能有效地复制,我错过了什么..?
#include <stdio.h>
#include <string.h>
int main()
{
char date[100];
char month[100];
char array[12][100] ={"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
char month2[100];
printf(" Please enter a date ");
fgets( date, 100, stdin);
strcpy(month2, month);
if( date[0] == '0' && date[1] == '1')
{
strcpy(month, array[0]);
}
else if( date[0] =='0' && date[1] == '2')
{
strcpy(month, array[1]);
}
else if( date[0] =='0' && date[1] == '3')
{
strcpy(month, array[2]);
}
else if( date[0] =='0' && date[1] == '4')
{
strcpy(month, array[3]);
}
else if( date[0] =='0' && date[1] == '5')
{
strcpy(month, array[4]);
}
else if( date[0] == '0' && date[1] == '6')
{
strcpy(month, array[5]);
}
else if( date[0] =='0' && date[1] == '7')
{
strcpy(month, array[6]);
}
else if( date[0] =='0' && date[1] == '8')
{
strcpy(month, array[7]);
}
else if( date[0] =='0' && date[1] == '9')
{
strcpy(month, array[8]);
}
else if( date[0] =='1' && date[1] == '0')
{
strcpy(month, array[9]);
}
else if( date[0] =='1' && date[1] == '1')
{
strcpy(month, array[10]);
}
else if( date[0] =='1' && date[1] == '2')
{
strcpy(month, array[11]);
}
printf("%s \n", month);
printf("%s \n", month2);
return 0;
}
【问题讨论】:
-
你对
strcpy(month2, month);有什么期望? -
你可能想要 strcat,因为 strcpy 只是在你每次复制到它时删除目标字符串。strcat 会追加。
-
month[12][100]中的100似乎有点矫枉过正;九月有 9 个字母,所以month[12][10]就足够大了。但是,它不会导致任何故障。当然最好将date[0]和date[1]转换为数字 (int n = (date[0] - '0') * 10 + (date[1] - '0');, and then usestrcpy(月,数组[n]);, possibly after validating that thedate[0]` 是'0'或'1',以及isdigit(date[1])。
标签: c