3abkareeno
3abkareeno

Reputation: 59

Converting string to three ints?

i have a c++ project which has a date class with three variables int day, month and 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

};

i want to know how to split the string date and assign the sub strings to the three variables int day, month and year

Upvotes: 1

Views: 69

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596602

You can use sscanf() or istringstream to parse the string.

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");
}

Upvotes: 6

Related Questions