Main Page   Class Hierarchy   Compound List   File List   Compound Members   File Members  

datepattern.C

Go to the documentation of this file.
00001 // $Id: datepattern_C-source.html,v 1.1 2001/04/16 17:42:58 dvermeir Exp $
00002 #include <stdlib.h> // for atoi()
00003 #include <ctype.h> // for isdigit()
00004 #include "datepattern.h"
00005 
00006 // Construct DatePattern containing first n components of p.
00007 DatePattern::DatePattern(const DatePattern& p,unsigned int n) {
00008 unsigned int m(min(p.size(),n));
00009 date_.resize(m);
00010 for (unsigned int i=0; i<m; ++i)
00011   date_[i] = p[i];
00012 }
00013 
00014 
00015 // Parses 1999-03-12 10:00, 1999-3-12, 1999-3, 1999
00016 bool
00017 DatePattern::parse(const string& s) {
00018 date_.clear();
00019 /* We use a simple brute-force procedure: copy the string
00020    to a C-string where we replace all non-digit chars with
00021    spaces. The repeatedly call strtol to parse this C string
00022    into a number of integers. See ``man strtol'' for details.
00023 */
00024 char    cs[s.size()+1];
00025 
00026 for (unsigned int i=0; i<s.size(); ++i)
00027   if (isdigit(s[i]))
00028      cs[i] = s[i];
00029   else
00030      cs[i] = ' ';
00031 cs[s.size()] = '\0';
00032 
00033 const char*     start(cs);
00034 char*           end(cs);
00035 unsigned int    n(0);
00036 
00037 do {
00038   start = end;
00039   long l(strtol(start,&end,10));
00040   if (end!=start) {
00041     ++n;
00042     if (l<0 || n>5) { // no negative stuff and no more than 5 numbers expected
00043       date_.clear();
00044       return false;
00045       }
00046     if (n<5) // only 4 numbers stored.
00047       date_.push_back(static_cast<unsigned int>(l));
00048     }
00049   }
00050 while (end!=start);
00051 return true;
00052 }
00053 
00054 void
00055 DatePattern::set(unsigned int year, unsigned int month, 
00056         unsigned int day, unsigned int hours) {
00057 date_.resize(4);
00058 date_[0] = year;
00059 date_[1] = month;
00060 date_[2] = day;
00061 date_[3] = hours;
00062 }
00063 
00064 ostream&
00065 operator<<(ostream& os,const DatePattern& date) {
00066 unsigned int sz(date.size());
00067 // Print in format year-month-day hours:00.
00068 if (sz>0) {
00069   os << date[0] ;
00070   if (sz>1) {
00071     os << "-" << date[1];
00072     if (sz>2) {
00073       os << "-" << date[2];
00074       if (sz>3)
00075         os << " " << date[3] << ":00";
00076       }
00077     }
00078   }
00079 return os;
00080 }
00081 

httpstats-stage04 [ 7 April, 2001]