我正在編寫一個程序,將短日期(mm/dd/yyyy)轉換爲長日期(2014年3月12日)並打印出日期。如何搜索字符串中的字符?
程序有工作給予以下用戶輸入: 2014年10月23日 2014年9月25日 2015年12月8日 2016年1月1日
我有計劃與工作第一個用戶輸入,但我不知道如何處理在字符串的第一個位置沒有「0」的用戶輸入。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string date;
cout << "Enter a date (mm/dd/yyyy): " << endl;
getline(cin, date);
string month, day, year;
// Extract month, day, and year from date
month = date.substr(0, 2);
day = date.substr(3, 2);
year = date.substr(6, 4);
// Check what month it is
if (month == "01") {
month = "January";
}
else if (month == "02") {
month = "February";
}
else if (month == "03") {
month = "March";
}
else if (month == "04") {
month = "April";
}
else if (month == "05") {
month = "May";
}
else if (month == "06") {
month = "June";
}
else if (month == "07") {
month = "July";
}
else if (month == "08") {
month = "August";
}
else if (month == "09") {
month = "September";
}
else if (month == "10") {
month = "October";
}
else if (month == "11") {
month = "November";
}
else {
month = "December";
}
// Print the date
cout << month << " " << day << "," << year << endl;
return 0;
}
我非常感謝任何幫助。
,而不是在預先確定的指標越來越子。尋找'/'索引並從那裏刪除。 – 2014-09-30 07:57:20
我想使用查找成員函數...像date.find(「/」,0)來尋找/字符和從位置0搜索。我仍然應該解析出月份,日期和年日期? – JimT 2014-09-30 08:06:05
@JimT ['find'](http://en.cppreference.com/w/cpp/string/basic_string/find)會爲您提供在'date.substr'調用中使用的偏移量,而不是固定值。 – zakinster 2014-09-30 08:08:29