Reading formated date from a file C++

你说的曾经没有我的故事 提交于 2019-12-12 05:38:00

问题


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.


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/37486311/reading-formated-date-from-a-file-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!