-1

Having this class:

date.hpp:

#ifndef DATE_HPP
#define DATE_HPP

#include <time.h>
#include <iostream>
#include <sstream>

class Date
{
    std::stringstream format;
    time_t date;
    struct tm *date_tm;

public:
    Date() : date(time(NULL)), date_tm(localtime(&date)) {}
    Date(std::istream &in);
    Date(std::string str);

    const std::string getDate();
    const bool dateMatch(std::string str);
};

#endif //DATE_HPP

And this ctors: date.cpp:

#include "date.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <regex>

bool isDate(std::string target)
{
    std::regex reg("[1-12]{2}/[1-31]{2}[00-99]{2}");
    return std::regex_search(target, reg);
}

Date::Date(std::istream &in)
{
    date_tm = new struct tm;
    std::cout << "enter date [mm/dd/yy]: ";
    format.basic_ios::rdbuf(in.rdbuf());

    if (isDate(format.str()))
    {
        format >> std::get_time(date_tm, "%m/%d/%y");
    }
    else
    {
        std::cout << "Format of date is not valid\n";
    }
}
...

If I try to use the ctor with std::istream argument:

#include "date.hpp"
#include <iostream>

using namespace std;

int main()
{
    Date d(cin);
    cout << d.getDate() << '\n';
}

Then the date format checks fails even before I can something write to cin. What is wrong now?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45

1 Answers1

0

You're format should be "%m/%d/%Y". See: https://en.cppreference.com/w/cpp/io/manip/get_time . Also your regex is missing a '/'. Plus your regex number ranges aren't quite right; they match a character class, not a number. "[1-12]" I think matches the one-character strings "1" and "2" only. You need to do something different with number ranges. You can check if the date parsing failed by checking whether format.fail() is true instead of running a regex. Plus I am skeptical of you're method of initializing format. It'd be better, I think, to just write

std::string s;
std::getline(std::cin, s);
std::stringstream format(s);

.

Anonymous1847
  • 2,568
  • 10
  • 16