這是任務:1)07/21/2003 2)2003 年 7 月 21 日
撰寫一個程式,讀取第一種格式的日期并以第二種格式列印它。
我應該使用字串方法,尤其是strtok。
這是我的代碼:
#include <stdio.h>
#include <string.h>
int main()
{
char date[20];
char month[20];
char day[20];
char year[20];
char *token;
char sep[1] = "/";
printf("Enter the date (MM/DD/YYYY): ");
gets(date);
token = strtok(date, sep);
if (token == "01")
{
strcpy(month, "Januray");
}
else if (token == "02")
{
strcpy(month, "February");
}
//continuing in this way
}
else if (token == "11")
{
strcpy(month, "November");
}
else
{
strcpy(month, "December");
}
token = strtok(NULL, sep);
strcpy(day, token);
token = strtok(NULL, sep);
strcpy(year, token);
printf("%s %s, %s", month, day, year);
}
問題是月份部分總是給出十二月,這意味著 if 陳述句不起作用。
uj5u.com熱心網友回復:
像這樣寫
if (token == "01")
不做你認為它做的事情,token指向字串的開頭(日期),所以你正在相互比較兩個地址,而不是使用 strcmp() 來比較實際的字串內容。
if (strcmp(token,"01") == 0)
但是上面的方法有點容易出錯,如果用戶輸入“1”呢?所以更好的方法是將其轉換為整數:
char* tokenend = NULL;
int mon = strtol(token, &tokenend, 10);
那么你可以mon在一個 switch 中使用它,這使代碼變得不那么冗長。
switch(mon) {
case 1:
strcpy(month,"January");
break;
...
default:
fprintf(stderr, "Invalid month entered %s", token);
break;
}
另請注意,strtok更改了內容,date因此原始日期不再存在。如果要保留原始字串,則需要單獨存盤。
一般來說,你應該使用fgets而不是gets從鍵盤讀取字串時使用,因為gets它不限制它可以讀取的字符數
if (fgets(date, sizeof(date), stdin) != NULL)
{
// and remove the \n
char* p = strchr(date,'\n');
if (p != NULL) *p = '\0';
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373029.html
上一篇:改變transform.position永遠不等于transform.position transform.forward
下一篇:滿足條件時處理兩種情況?
