-1

So I have this file with multiple dates like this:

2.10.2015
13.12.2016
...

I'm wondering how to read from this file and store day, month and year into 3 separate integers.

Thanks.

xxm0dxx
  • 115
  • 1
  • 10
  • 3
    What have you tried? This is pretty simple since the stream will read `int` values and you can consume the individual `.` delimiters between them via `char`. – James Adkison May 27 '16 at 14:47

2 Answers2

5

Given an istream foo which contains the dates you'll want to use get_time:

vector<tm> bar;
tm i;

while(foo >> get_time(&i, "%d.%m.%Y")) bar.push_back(i);

Live Example

Of course defensive input is best practice, and doing that can be very challenging for a complex input type like a date. If you're going for that you might find this helpful: https://stackoverflow.com/a/29413535/2642059

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
-1

You could try something like this:

// construct stream object and open file 
std::ifstream ifs(file_name.c_str());

// check if opened successfully
if (!ifs) std::cerr <<"Can't open input file!\n";

int year, month, day;
char dot;

// extract date
ifs >> day >> dot >> month >> dot >> year;

// check input format
if (dot != '.') // add ranges for month and days validity
{
    std::cerr <<"Wrong date format!\n";
}

The above code could be placed in a (while) loop reading the file line by line.

Ziezi
  • 6,375
  • 3
  • 39
  • 49