c++ - 在 C++ 中解析字符串,接受单数和双数日期格式

标签 c++

当将用户的输入作为日期时,我希望能够提取数字,无论格式是 mm/dd/yy 还是 m/d/yy。我只能弄清楚如何做一个或另一个,但不能同时做。我该怎么办?我是来自 python 的 C++ 新手。这是我的代码。

#include <iostream>
#include <string>
using namespace std;



bool isMagicDate(string year, string month, string day)

{       
int int_month = stoi(month);
int int_day  = stoi(day);
int int_year = stoi(year);

if (int_month * int_day == int_year)
    return true;

else return false;
}   


int main()
{
string date;

cout << "enter a date in the format mm/dd/yy: " << endl;
cin >> date;


string month = date.substr(0,2);
string day = date.substr(3,2);
string year = date.substr(6,2);

cout << "the month is " << month  << endl 
     << "the day is " << day  << endl
     << "the year is " << year << endl;

cout << "the date you entered is " << date << endl;

bool magic = isMagicDate(year, month, day);

cout << "Is the date magic? " << magic << endl;


return 0;
}

最佳答案

您可以使用 std::istringstream解析日期字符串,例如:

#include <iostream>
#include <string>
#include <sstream>

bool isMagicDate(int year, int month, int day)
{       
    return ((month * day) == year);
}   

int main()
{
    std::string date;

    std::cout << "enter a date in the format mm/dd/yy: " << std::endl;
    std::cin >> date;

    int month, day, year;
    char slash1, slash2;

    std::istringstream iss(date);
    if ((iss >> month >> slash1 >> day >> slash1 >> year) &&
        (slash1 == '/') && (slash2 == '/'))
    {
        std::cout << "the date you entered is " << date << std::endl;

        std::cout << "the month is " << month << std::endl 
             << "the day is " << day  << std::endl
             << "the year is " << year << std::endl;

        bool magic = isMagicDate(year, month, day);

        std::cout << "Is the date magic? " << magic << std::endl;
    }
    else
        std::cout << "invalid date entered!" << std::endl;

    return 0;
}

或者,在 C++11 及更高版本中,您可以使用 std::get_time I/O 操纵器代替:

#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    std::cout << "enter a date in the format mm/dd/yy: " << std::endl;

    std::tm t = {};
    if (std:cin >> std::get_time(&t, "%m/%d/%y"))
    {
        std::cout << "the date you entered is " << std::put_time(&t, "%c") << std::endl;

        std::cout << "the month is " << tm.tm_mon+1 << std::endl 
             << "the day is " << tm.tm_mday << std::endl
             << "the year is " << tm.tm_year << std::endl;

        // use tm as needed ...
    }
    else
        std::cout << "invalid date entered!" << std::endl;

    return 0;
}

关于c++ - 在 C++ 中解析字符串,接受单数和双数日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788797/

相关文章:

将分数转换为二进制的 C++ 代码

c++ - char数组-处理内存

c++ - 模板类二重载函数

string - find_if 在字符串数组上

c++ - 如何减少逻辑表达式?

c++ - 如何覆盖 [] 使我的类看起来就像一个 3 维矩阵

c++ - SFINAE:检测成员变量的存在在 g++ 上不起作用

c++ - MFC:如何将自定义控件包含到 Visual Studio 的工具箱中

c++ - 如何在编译时标记默认参数的所有使用

c++ - GCC STL_tree.h std::set 的红黑树源代码