我正在编写一个程序,我需要从文件中读取日期。日期是年、月和日。我需要如何阅读所有日期信息?可以举一些例子吗??
5 回答
首先,您可能需要一个结构来保存这些值。有一个标准结构,tm,但是这个有很多成员,其中一些依赖于其他的,当 yday 与 wday 和 mday 不一致时会令人困惑。
struct Date {
int year;
int month;
int day;
};
然后,您需要一个能够将数据读入结构的函数。您首先需要打开文件,读取第一行并处理它。为了实现这一点,您可以使用 ifstream,它是 C++ 中用于读取文件的标准类。
std::ifstream f( fileName.c_str() );
然后您需要读取存储日期的行。因为它是一个练习,我认为它是第一个。getline()
从输入中读取整行并将其存储在先前创建的字符串中。
std::string line;
std::getline( f, line );
最后,您必须处理该行。有多种方法可以实现这一点,但可能在 C++ 中最舒服的一种方法是使用与字符串相关的流,并按其类型读取每个字段。
std::istringstream str( line );
str >> date.year
>> firstDot
>> date.month
>> lastDot
>> date.day
;
关于错误检查,您可以进行各种验证(我将把它留给您)。至少,我们应该检查我们是否在应该读取点作为分隔符。
if ( firstDot != '.'
|| lastDot != '.' )
{
date.year = date.month = date.day = -1;
}
这是整个功能:
bool readDate(const std::string &fileName, Date &date)
{
char firstDot;
char lastDot;
std::ifstream f( fileName.c_str() );
bool toret = false;
date .year = date.month = date.day = -1;
if ( f.is_open() ) {
std::string line;
// Read line containing the date
std::getline( f, line );
// Chk string
std::istringstream str( line );
str >> date.year
>> firstDot
>> date.month
>> lastDot
>> date.day
;
if ( firstDot != '.'
|| lastDot != '.' )
{
date.year = date.month = date.day = -1;
}
else toret = true;
}
return toret;
}
如您所见,错误条件由函数的返回值以及struct Date的内容发出信号。
希望这可以帮助。
如果您有 C++0x std::lib (不必太新),这里有一个免费、简单且小型的库解决方案(1 个源代码,1 个标头):
http://howardhinnant.github.io/date.html
这是示例用法:
#include "date.h"
#include <iostream>
#include <sstream>
int main()
{
using namespace gregorian;
date d;
std::istringstream in("2011.02.07");
in >> date_fmt("%Y.%m.%d") >> d;
if (in.fail())
std::cout << "failed\n";
else
std::cout << date_fmt("%A %B %e, %Y") << d << '\n';
}
输出:
Monday February 7, 2011
语法遵循 C 的 strftime 函数。日期库需要 C++0x 头文件<cstdint>
和 2006 年的一些补充time_get
。
我建议使用strptime。我不知道您希望使用哪种内部格式进行约会,但这应该适合您。请注意,它不会进行任何错误检查。
struct tm tm;
time_t t;
strptime("%Y:%m:%d", &tm);
printf("year: %d; month: %d; day: %d;\n",
tm.tm_year, tm.tm_mon, tm.tm_mday);
t = mktime(&tm);
使用 Boost 就是一个答案。
This question is similar and has a very good answer,虽然不完全适合你的问题。
#include <fstream>
#include <iostream>
#include <string>
#include <boost/date_time.hpp>
using std::cout;
using std::cin;
using std::endl;
using std::string;
namespace bt = boost::posix_time;
int main()
{
string dd=" 12 December 2011 15:00:42";
//string dd="December 2011 15:00:42";
cout<<dd<<endl;
std::stringstream time1is(dd);
std::locale dForm = std::locale(std::locale::classic(),new bt::time_input_facet("%d %B %Y %H:%M:%S"));//12 December 2011 15:00:42
time1is.imbue(dForm);
bt::ptime t1;
if ((time1is>>t1).fail()) {
std::cerr<<"error while parsing "<<dd<<std::endl;
}else{
std::cerr<<"success!! "<<dd<<std::endl;
}
cout<<t1<<endl;
}
//char c; cin >> c;
return 0;
}
你也可以用“.”分割字符串。字符并将数据放入变量中(例如可能是数组)。
然后,您可以通过组合它们来创建自己的格式和字符串。