Extract integers from a string

Hello everyone!
I am trying to extract some integers from a string, already written or written by the user, in which there is a character between two numbers.
The string could be a date for example, like that:

string date = "27/04/2010";

I would like to extract 27, 04 and 2010 in three integers.
I know in C language there's a useful function that let to extract whatever you want from a line, for example, ignoring specific characters.
I read that in C++ you can use stringstream, but I didn't find how to do that.
Would you help me, please?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

void splitDate( string s, int &day, int &month, int &year )
{
   char c;
   stringstream( s ) >> day >> c >> month >> c >> year;
}

int main()
{
   string date;
   int day, month, year;

   cout << "Enter date as dd/mm/yyyy: ";   cin >> date;
   splitDate( date, day, month, year );
   cout << "Day:   " << day   << endl;
   cout << "Month: " << month << endl;
   cout << "Year:  " << year  << endl;
}


Enter date as dd/mm/yyyy: 27/04/2017
Day:   27
Month: 4
Year:  2017


It is very sensitive to input though (no internal spaces, please). You may want to filter any spaces from the string first.
One way to do.
1
2
3
4
5
6
7
8
9
10
  string date = "27/04/2010";
  istringstream iss(date);

  int day, month, year;
  char sep;

  iss >> day >> sep >> month >> sep >> year;

  cout << "values: " << "Day: " << day << " month: " << month 
       << " Year: " << year << "\n\n";


It works for this particular example. In real code you need to check the format of the string first.
with std::regex_token_iterator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string date = "27/04/2010";
    std::regex rgx("/+");
    std::sregex_token_iterator iter(date.begin(), date.end(), rgx, -1);
    std::sregex_token_iterator last{};
    for ( ; iter != last; ++iter)
    std::cout << *iter << '\n';
}
//http://en.cppreference.com/w/cpp/regex/regex_token_iterator 
Perfect, it works!
Thank you all!! Have a nice day :D
Topic archived. No new replies allowed.