我是C++的初学者,我试图提示用户以XX/XX格式输入月份和年份,并打印所写的日期,日期和季节。虽然,我不知道如何在一行中输入特定格式XX/XX的值。例如,01/22表示1月22日。另外,我使用了switch语句,因为它是我正在研究的章节的重点,所以我想保持这种方式。
#include <iostream>
using namespace std;
int main()
{
int month, day;
cout << "Enter the date in XX/XX: \n";
cin >> month;// Using a "space bar" instead of "enter" prevents the new line in cin
cout << "/";
cin >> day;
switch (month)
{ // The integers don't accept the single quotes '1'
case 1: cout << "The date entered is January " << day << ". The season is winter.\n0"; break;
case 2: cout << "The date entered is February " << day << ". The season is spring.\n"; break;
case 3: cout << "The date entered is March " << day << ". The season is spring.\n"; break;
case 4: cout << "The date entered is April " << day << ". The season is spring.\n"; break;
case 5: cout << "The date entered is May " << day << ". The season is spring.\n"; break;
case 6: cout << "The date entered is June " << day << ". The season is summer.\n"; break;
case 7: cout << "The date entered is July " << day << ". The season is summer.\n"; break;
case 8: cout << "The date entered is August " << day << ". The season is summer.\n"; break;
case 9: cout << "The date entered is September " << day << ". The season is fall.\n"; break;
case 10: cout << "The date entered is October " << day << ". The season is fall.\n"; break;
case 11: cout << "The date entered is November " << day << ". The season is winter.\n"; break;
case 12: cout << "The date entered is December " << day << ". The season is winter.\n"; break;
default: cout << "The input is invalid.\n" << endl; break;
}
return 0;
}
我试着写cin >> month >> day;
,但我没有收到我想要的格式输入,我想要的,01/22。我也试过
cin >> month;
cout << "/";'
cin >> day;
但这需要我按回车键,然后它创建了一个新行。
3条答案
按热度按时间72qzrwbm1#
标准库有一个名为
std::get_time
的I/O操作器,专门用于阅读这样的日期和时间。还有一个匹配的std::put_time
用于打印日期和时间。要像这样获取月份和日期,您可以使用以下命令:运行此命令,我输入:
03/22
作为输入,得到:作为输出。
输入日期后,月份将以整数形式存储在
input.tm_mon
中,月份的日期将以整数形式存储在input.tm_mday
中。正如您所看到的,它已经有了将月份数字转换为名称的代码(以及读取月份名称)。月份名称也是本地化的,因此您可以设置以指定的语言显示月份名称,或者半自动地使用用户首选的语言(但翻译字符串的其余部分取决于您)。83qze16e2#
C++20答案:
qlckcl4x3#
最简单的方法就是
slash
变量读取输入中的斜杠字符。现在这个方法不做任何错误检查,但似乎是初学者的最佳选择。
更复杂的方法是将输入作为字符串读取,然后解析所述字符串或重复中建议的方法。