【问题标题】:Converting string to three ints?将字符串转换为三个整数?
【发布时间】:2014-10-06 06:15:13
【问题描述】:

我有一个 c++ 项目,它有一个日期类,其中包含三个变量 int 日、月和年

class date{
  int day;
  int month;
  int year;
    public:
  date(); // default constructor
  date(int, int, int); // parameterized constructor with the three ints
  date(string) // this constructor takes a date string "18/4/2014" and assigns 
                  18 to intday, 4 to int month and 2014 to int year

};

我想知道如何拆分字符串日期并将子字符串分配给三个变量int day、month和year

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可以使用sscanf()istringstream 来解析字符串。

    date::date(string s)
      : day(0), month(0), year(0)
    {
        int consumed;
        if (sscanf(s.c_str(), "%d/%d/%d%n", &day, &month, &year, &consumed) == 3)
        {
            if (consumed == s.length())
                return;
        }
        throw std::runtime_error("invalid input");
    }
    

    date::date(string s)
      : day(0), month(0), year(0)
    {
        char ignore;
        std::istringstream iss(s);
        iss >> day >> ignore >> month >> ignore >> year;
        if (!iss || !iss.eof())
          throw std::runtime_error("invalid input");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2012-02-21
      • 2010-12-31
      相关资源
      最近更新 更多