0

I have a string

string date="DD/MM/YYYY";

how do i get three numbers

day=atoi(DD);
month=atoi(MM);
year=atoi(YYYY);

thx

JohnnyF
  • 1,053
  • 4
  • 16
  • 31
  • 2
    See here please: [Why does reading a struct record fields from std::istream fail, and how can I fix it?](http://stackoverflow.com/questions/23047052/why-does-reading-a-struct-record-fields-from-stdistream-fail-and-how-can-i-fi) or also [Split a string in C++?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – πάντα ῥεῖ Dec 26 '14 at 19:53
  • If the string will always have that same format then you just need to do atoi on substrings for each of the positions. – Rodrigo Gómez Dec 26 '14 at 19:54
  • General solution of parsing string into parts: http://stackoverflow.com/a/236803/1566267 and use `int` instead of `string` both for `elems` and `item`: `elems.push_back(atoi(item.c_str()))`; – John_West Dec 26 '14 at 20:08

3 Answers3

2
int d=0, m=0, y=0;
sscanf(date.c_str(),"%d/%d/%d",&d,&m,&y); 
Hans Klünder
  • 2,176
  • 12
  • 8
2

Using a custom manipulator I'd do this

if (std::istringstream(date) >> std::noskipws
    >> day >> slash >> month >> slash >> year) {
    ...
}

The manipulator would look something like this:

std::istream& slash(std::istream& in) {
    if (in.peek() != '/') {
        in.setstate(std::ios_base::failbit);
    }
    return in;
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

Or you can do it in this way,

int day = atoi(date.substr(0,2).c_str());
int month = atoi(date.substr(3,2).c_str());
int year = atoi(date.substr(6,4).c_str());

Using c_str() is because atoi takes char* and c_str() makes this.

Wesam Adel
  • 13
  • 3
  • You could do `int day = std::stoi(data.substr(0, 2));`. Sadly, these functions don't expose a way to verify that conversion is successful. – Dietmar Kühl Dec 26 '14 at 20:52
  • Yes, but I think the given format -or as i understand- ensures the function will work properly, I think The string given may be checked to contain only slashes and decimal digits. – Wesam Adel Dec 26 '14 at 21:20