如何在 c++ 中在同一行上输入

How to take input on same line in c++?

本文关键字:一行 输入 c++      更新时间:2023-10-16

我想以这种格式输入日期 2/11/2015。 我如何使用 C++?谢谢 以下方法不起作用。

cin>>day >>month >>year ;

而且用户也不必按回车键。

我的代码是

#include <iostream>
using namespace std;
class Date
{
private :
    int day,month,year;
    char slash;
public :
    void inputdate(void)
    {
        cout<<"Enter Date in Formate (day/month/year)"<<endl;
        cin >> day >> slash >> month >> slash >> year;
    }
    void checkdate(void)
    {
        if (day<=0 || day>=32)
        {
            cout<<"Day is Wrong ! "<<endl;
        }
        if (month==2 && day>=29)
        {
            cout<<"February can have max 28 days !"<<endl;
        }
        if (month<=0 || month>=13)
        {
            cout<<"Month is wrong !"<<endl;
        }
        if (year<=1799 || year>=3000)
        {
            cout<<"Year is Wrong !"<<endl;
        }
        if ((month==4 || month==6 || month==9 || month==11)&&(day>30))
        {
            cout<<"Day is wrong ! September ,April ,June and November can have maximum 30 days ."<<endl;
        }
    }
    void showdate(void)
    {
        checkdate();
        cout<<"Date is : "<<day<<"/"<<month<<"/"<<year<<endl;
    }
};
C++本身并不

理解文本日期;您需要使用提供此功能的库,或者自己创建一个函数来在文本格式和内部整数格式之间进行转换(通常是自"纪元"(1970 年 1 月 1 日 00:00(以来的秒数或毫秒数,具体取决于平台(。

为此,您需要:

  • 将日期收集为单个字符串或字符数组
  • 将日期分隔为其组成日/月/年
  • 将此日期计算为自纪元以来的秒数

说了这么多,使用库的第一个选项可能是最好的,因为它还将包含字符串和内部日期格式之间切换的功能;你选择哪个库取决于你,很大程度上取决于你编码的平台。

您可以使用

虚拟char变量读取/分隔符:

int day, month, year;
char slash; // dummy to skip past the '/'
cin >> day >> slash >> month >> slash >> year;