назначение с помощью sscanf в C ++ - PullRequest
0 голосов
/ 03 ноября 2018

Может ли кто-нибудь указать, если есть, ошибка в моем коде, потому что эта проблема заняла у меня довольно много времени, и я действительно новичок в программировании на C ++.
Таким образом, bool valid_str проверяет, является ли строка действительной, поэтому формат даты действительный имеет значение ex: 2016-07-08 / 01: 00 , недействительно 2016-7-8 / 01: 00
В конструкторе Date со строкой, если формат недействителен, тогда присвойте всем 0. Если он действителен, тогда присвойте его переменным, это просто кусок большого кода, но я думаю, что я испортил sscanf, следовательно, получаю Ошибка RunTime (я использую Linux). Я правильно использовал?

bool valid_str(const std::string& str)
{
    int len = str.size();
    if (len != 16)
        return false;
    if (str[4] != '-')
        return false;
    if (str[7] != '-')
        return false;
    if (str[10] != '/')
        return false;
    if (str[13] != ':')
        return false;

    for (int i = 0; i < 4; i++) {
        if (str[i] < '0' || str[i] > '9')
            return false;
    }

    for (int i = 5; i < 7; i++) {
        if (str[i] < '0' || str[i] > '9')
            return false;
    }

    for (int i = 8; i < 10; i++) {
        if (str[i] < '0' || str[i] > '9')
            return false;
    }

    for (int i = 11; i < 13; i++) {
        if (str[i] < '0' || str[i] > '9')
            return false;
    }

    for (int i = 14; i < 16; i++) {
        if (str[i] < '0' || str[i] > '9')
            return false;
    }

    return true;
}

//Date Constructor

Date::Date(const std::string& dateString)
{
    std::string str;
    if (valid_str(dateString) == false) {
        this->m_year = 0;
        this->m_month = 0;
        this->m_day = 0;
        this->m_hour = 0;
        this->m_minute = 0;
    }
    else {
        sscanf(dateString.c_str(), "%4d-%2d-%2d/%2d:%2d",
            &m_year,
            &m_month,
            &m_day,
            &m_hour,
            &m_minute);
    }
}  

(РЕДАКТИРОВАНИЕ) ПОЛНЫЙ КОД:

#include "Date.hpp" 
//#include <initializer_list> 
//#include <string> 
#include <iomanip>
#include <stdio.h>

//using namespace std;
//bool valid_str(std::string &);

 Date::Date(){ } //default constructor 

 /**
  * @brief constructor with arguments
  */
Date::Date(int t_year, int t_month, int t_day, int t_hour, int t_minute) {
m_year = t_year; 
m_month = t_month; 
m_day = t_day; 
m_hour = t_hour; 
m_minute = t_minute; 
}

bool valid_str(const std::string& str) { 
    int len = str.size(); 
    if(len != 16) 
    return false; 
    if(str[4] != '-') 
    return false; 
    if(str[7] != '-') 
    return false; 
    if(str[10] != '/') 
    return false; 
    if(str[13] != ':') 
    return false; 

    for(int i = 0 ; i < 4 ; i++) { 
        if(str[i] < '0' || str[i] > '9') 
        return false; 
        } 

        for(int i = 5 ; i < 7 ; i++) { 
            if(str[i] < '0' || str[i] > '9') 
            return false; 
            } 

            for(int i = 8 ; i < 10 ; i++) { 
                if(str[i] < '0' || str[i] > '9') 
                return false;
                 } 

                for(int i = 11 ; i < 13 ; i++) { 
                    if(str[i] < '0' || str[i] > '9') 
                    return false; 
                    } 

                    for(int i = 14 ; i < 16 ; i++) { 
                        if(str[i] < '0' || str[i] > '9') 
                        return false; 
                        } 

                        return true; 
                        }


 /**
  * @brief constructor with a string
  */
Date::Date(const std::string &dateString)
{ 
    std::string str;
     if(valid_str(dateString) == false) {
          this->m_year = 0; 
          this->m_month = 0; 
          this->m_day = 0; 
          this->m_hour = 0; 
          this->m_minute = 0; 
          } else{ 
              sscanf(dateString.c_str(), "%4d-%2d-%2d/%2d:%2d",
        &m_year,
        &m_month,
        &m_day,
        &m_hour,
        &m_minute);

                  }
                }

int Date::getYear(void) const
{
    return m_year;
}

void Date::setYear(const int t_year){
    m_year = t_year;
}

int Date::getMonth(void) const{
    return m_month;
}

void Date::setMonth(const int t_month){
    m_month = t_month;
}

int Date::getDay(void) const{
    return m_day;
}

void Date::setDay(const int t_day){
    m_day = t_day;
}

  int Date::getHour(void) const{
      return m_hour;
  }

    void Date::setHour(const int t_hour){
        m_hour = t_hour;
    }

      int Date::getMinute(void) const{
          return m_minute;
      }

      void Date::setMinute(const int t_minute){
        m_minute = t_minute;
      }

      int leapYear(int y){
       if (y % 400 == 0)
        return 1;
        if (y %4 == 0 && y % 100 == 0){
        return 1;
        }else 
        return 0;
    }

     bool Date::isValid(const Date &t_date){
        int x[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        x[1] += leapYear(t_date.m_year);

        if(t_date.m_year < 1000 || t_date.m_year > 9999){
            return false;
        }else if (t_date.m_month < 1 || t_date.m_month > 12){
            return false;
        }else if(t_date.m_day < 1 || t_date.m_day > x[t_date.m_month - 1]){
            return false;
        }else if(t_date.m_hour > 24 || t_date.m_hour < 0){
            return false;
        }else if(t_date.m_minute > 59 || t_date.m_minute < 0){
            return false;
        }else return true;
            }

/**
  *  @brief overload the assign operator
  */
Date& Date::operator=(const Date &t_date){
        this->m_year = t_date.m_year;
        this->m_month = t_date.m_month;
        this->m_day = t_date.m_day;
        this->m_hour = t_date.m_hour;
        this->m_minute = t_date.m_minute;
}
/**
  * @brief check whether the CurrentDate is  greater than the t_date
  */
bool Date::operator>(const Date &t_date) const{
    if(this->m_year > t_date.m_year){
        return true;
    }else if(this->m_month > t_date.m_month){
        return true;
    }else if(this->m_day > t_date.m_day){
        return true;
    }else if(this->m_hour > t_date.m_hour){
        return true;
    }else if(this->m_minute > t_date.m_minute){
        return true;
    }else return false;
}

/**
  * @brief check whether the CurrentDate is  less than the t_date
  */
bool Date::operator<(const Date &t_date) const{
    if(this->m_year < t_date.m_year){
        return true;
    }else if(this->m_month < t_date.m_month){
        return true;
    }else if(this->m_day < t_date.m_day){
        return true;
    }else if(this->m_hour < t_date.m_hour){
        return true;
    }else if(this->m_minute < t_date.m_minute){
        return true;
    }else return false;
}


 /**
  * @brief check whether the CurrentDate is  greater or equal than the t_date
  */
  bool Date::operator>=(const Date &t_date) const{
      if (*this > t_date || *this == t_date)
        return true;
    else
        return false;
  }


  /**
  * @brief check whether the CurrentDate is  less than or equal to the t_date
  */
  bool Date::operator<=(const Date &t_date) const{
       if (*this < t_date || *this == t_date)
        return true;
    else
        return false;
  }

/**
  * @brief check whether the CurrentDate is equal to the t_date
  */
bool Date::operator==(const Date &t_date) const{
    if (this->m_year == t_date.m_year)
        return true;
    if (this->m_month == t_date.m_month)
        return true;
    if (this->m_day == t_date.m_day)
        return true;
    if (this->m_hour == t_date.m_hour)
        return true;
    if (this->m_minute == t_date.m_minute)
        return true;
    return false;
}


Date Date::stringToDate(const std::string &t_dateString){
    int y = 0, m = 0, d = 0, h = 0, mm = 0;
    sscanf(t_dateString.c_str(), "%d-%d-%d/%d:%d", y, m, d, h, mm);
    return Date(y, m, d, h, mm);
}

std::string Date::dateToString(const Date &t_date){
    char c[30];
    sscanf(c, "%4d-%2d-%2d/%2d:%2d", t_date.m_year, t_date.m_month, t_date.m_day, t_date.m_hour, t_date.m_minute);
    return std::string(c);
}

1 Ответ

0 голосов
/ 03 ноября 2018

В качестве справки, он компилируется и выполняется без проблем в Windows 10 с Версия компилятора MS 19.15.26732.1 x64

uint32_t m_year = 0;
uint32_t m_month = 0;
uint32_t m_day = 0;
uint32_t m_hour = 0;
uint32_t m_minute = 0;

constexpr char datestring[] = "2016-07-08/01:00";
constexpr char invalid[] = "2016-7-8/01:00";
constexpr char format[] = "%4u-%2u-%2u/%2u:%2u";

void getdate(const char date[])
{
    int32_t result = sscanf(date, format, 
        &m_year,
        &m_month,
        &m_day,
        &m_hour,
        &m_minute);

    _ASSERT(result == 5);
    _ASSERT(m_year == 2016);
    _ASSERT(m_month == 7);
    _ASSERT(m_day == 8);
    _ASSERT(m_hour == 1);
    _ASSERT(m_minute == 0);
}

int wmain()
{
    getdate(datestring);
    getdate(invalid);

    std::string_view sw{datestring};
    getdate(sw.data());
    std::string str{datestring};
    getdate(str.c_str());
}
...