2017-04-11 104 views
0

我試圖將以dd/mm/yyyy格式輸入的日期更改爲月份日,年格式,並且我已經完成了大部分操作,但是我的輸出在添加了額外的奇怪字符之後那天。這是我的代碼C中的日期格式

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
    char userDate[11]; 
    char dateWord[11]; 
    char day[2]; 
    char year[4]; 
    printf("Welcome to the Date Formatter.\nPlease input a date in the form of mm/dd/yyyy.\n"); 
    scanf("%s", userDate); 

    day[0] = userDate[3]; 
    day[1] = userDate[4]; 
    year[0] = userDate[6]; 
    year[1] = userDate[7]; 
    year[2] = userDate[8]; 
    year[3] = userDate[9]; 

    if (userDate[0] == '0' && userDate[1] == '1') 
     strcpy(dateWord, "January"); 
    if (userDate[0] == '0' && userDate[1] == '2') 
     strcpy(dateWord, "February"); 
    if (userDate[0] == '0' && userDate[1] == '3') 
     strcpy(dateWord, "March"); 
    if (userDate[0] == '0' && userDate[1] == '4') 
     strcpy(dateWord, "April"); 
    if (userDate[0] == '0' && userDate[1] == '5') 
     strcpy(dateWord, "May"); 
    if (userDate[0] == '0' && userDate[1] == '6') 
     strcpy(dateWord, "June"); 
    if (userDate[0] == '0' && userDate[1] == '7') 
     strcpy(dateWord, "July"); 
    if (userDate[0] == '0' && userDate[1] == '8') 
     strcpy(dateWord, "August"); 
    if (userDate[0] == '0' && userDate[1] == '9') 
     strcpy(dateWord, "September"); 
    if (userDate[0] == '1' && userDate[1] == '0') 
     strcpy(dateWord, "October"); 
    if (userDate[0] == '1' && userDate[1] == '1') 
     strcpy(dateWord, "November"); 
    if (userDate[0] == '1' && userDate[1] == '2') 
     strcpy(dateWord, "December"); 


    printf("The date is:\n"); 
    printf("%s %s, %s\n", dateWord, day, year); 
} 

,輸出是

c:\CompSci\C Programming>dateconvert 
Welcome to the Date Formatter. 
Please input a date in the form of mm/dd/yyyy. 
01/23/1998 
The date is: 
January 23╢ , 1998 

我不知道正在打印的╢是爲什麼。

+4

'char day [2];' - >'char day [3];'then'day [2] ='\ 0''。否則,你在'天'中沒有有效的字符串。 'year'同樣的問題。 – kaylum

+0

哇,我覺得那愚蠢的..非常感謝你! – jpantalion

+1

習慣這種感覺 - 它不會是最後一次':)' –

回答

5

已經有日期解析和格式化功能,strptimestrftime。所以你可以使用它們。首先,使用strptime將日期解析爲struct tm。現在

#include <time.h> 

struct tm date; 
strptime(userDate, "%m/%d/%Y", &date); 

的日期是在struct tm,並從那裏你可以用正常的日期功能,包括strftime進行格式化操作它。

char formatted_date[40]; 
strftime(formatted_date, 40, "%B %d, %Y", &date); 
puts(formatted_date); 

對使用​​strftime是會兌現的用戶的語言環境,並在適當的語言提供一個月的好處。 C默認情況下不支持區域設置,您必須從locale.h調用setlocale (LC_ALL, "");

$ ./test 
Welcome to the Date Formatter. 
Please input a date in the form of mm/dd/yyyy. 
01/02/1999 
January 02, 1999 

$ LC_ALL=es_ES ./test 
Welcome to the Date Formatter. 
Please input a date in the form of mm/dd/yyyy. 
01/02/1999 
enero 02, 1999 

請注意,您應該scanf僅限於userDate緩衝區的大小否則它可以使緩衝區溢出。 %s應該總是有一個限制。

scanf("%10s", userDate); 

雖然有些編譯器會接受void main,但它是非標準的。它應該始終是int main