将字符串转换为三个整数?

时间:2014-08-13 01:44:53

标签: c++

我有一个c ++项目,其日期类包含三个变量int day,month和year

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三个变量

1 个答案:

答案 0 :(得分:6)

您可以使用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");
}