写一个c++程序根据美国标准输入日期:月/日/年 或英文标准:日期/月/年 输出中文标准的日期:年月日 如果月份的数字无效,则应输出“月份错误”;如果日期编号无效,则应输出"day erro产”;如果月份和日期都无效,则只输出'month error”即可。
时间: 2024-09-14 07:10:58 浏览: 55
ISO/IEC 14882:2014 C++14 C++标准 英文版 PDF 非扫描版
5星 · 资源好评率100%
Here's a C++ program that takes input in the format of American or English standard (month/day/year) and outputs it in the Chinese standard format (year/month/day). The program includes input validation for month, day, and checks for invalid inputs.
```cpp
#include <iostream>
#include <sstream>
std::string parseDate(const std::string &input) {
std::istringstream iss(input);
int year, month, day;
if (!(iss >> day >> '/' >> month >> '/' >> year)) { // Check for valid date format
if (iss.fail()) {
return "day error";
} else if (!iss.eof()) { // If there's still data left after reading the day, it's a month error
return "month error";
}
}
// Validate month (1-12)
if (month < 1 || month > 12) {
return "月份错误";
}
return std::to_string(year) + "/" + std::to_string(month) + "/" + std::to_string(day);
}
int main() {
std::string input_date;
std::cout << "请输入日期 (月/日/年): ";
getline(std::cin, input_date);
std::string result = parseDate(input_date);
if (result != "month error") {
std::cout << "转换后的日期: " << result << std::endl;
} else {
std::cerr << result << std::endl;
}
return 0;
}
```
To run this program, copy the code into a C++ file, compile and then enter your desired input when prompted. The program will validate the input and display the output accordingly.
阅读全文