0

I've been working on a project that takes a user input in date format, such as "05/10/1996", and then parses it into three integers. One for month, one for day, and one for year. I was looking at the function getline() but wasn't quite sure how to use it to parse multiple objects at once. Is there a way to do this with a while loop? If so, I would appreciate some help cause i'm kind of stuck on this.

emufossum13
  • 377
  • 1
  • 10
  • 21
  • 2
    See http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c on how to split a string into tokens (in this case, you'd use "/" as the delimiter.) – Nikos C. Oct 27 '13 at 02:10

2 Answers2

1

Here is one of the way -

void split(std::vector<std::string> &tokens, const std::string &text, char sep) {
    int start = 0, end = 0;
    while ((end = text.find(sep, start)) != std::string::npos) {
        tokens.push_back(text.substr(start, end - start));
        start = end + 1;
    }
    tokens.push_back(text.substr(start));
}

Usage -

int main(int argc, const char * argv[]) {

    std::vector<std::string> tokens;

    std::string *text = new std::string("05/10/1996");

    split(tokens, *text, '/');

    int first = atoi(tokens[0].c_str());
    int second = atoi(tokens[1].c_str());
    int third = atoi(tokens[2].c_str());

    std::cout<<first<<std::endl;
    std::cout<<second<<std::endl;
    std::cout<<third<<std::endl;

    while (true);

    return 0;
}

Which outputs this on console using integer variables -

5 10 1996

For advanced solution/discussions - Refer this question.

Community
  • 1
  • 1
Ashok
  • 6,224
  • 2
  • 37
  • 55
0
int m,d,y;
char dummy;
cin >> m >> dummy >> d >> dummy >> y;
Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49