ex00 edge cases and execute function

This commit is contained in:
2026-04-24 01:20:07 +02:00
parent 7afb0335ef
commit c28623442e
7 changed files with 132 additions and 6 deletions

View File

@@ -63,8 +63,116 @@ void BitcoinExchange::readDatabase(std::ifstream &db)
date = line.substr(0, pos);
price = line.substr(pos + 1);
this->data[date] = std::strtod(price.c_str(), NULL);
}
}
void BitcoinExchange::execute(std::ifstream &db)
{
std::string line;
std::getline(db, line);
if (line != "date | value")
throw std::exception();
size_t pos;
std::string date;
std::string value;
while (std::getline(db, line))
{
pos = line.find('|');
if (pos == std::string::npos)
{
cout << "Error: bad input => " << line << endl;
continue;
}
date = line.substr(0, pos - 1);
value = line.substr(pos + 2);
if (!validateAll(date, value))
continue ;
std::map<std::string, double>::iterator it = this->data.lower_bound(date);
if (it == this->data.begin() && it->first != date)
{
cout << "Error: bad input => " << date << endl;
continue;
}
if (it->first != date)
it--;
cout << date << " => " << value << " = " << it->second * std::strtod(value.c_str(), NULL) << endl;
}
}
bool BitcoinExchange::validateAll(const std::string &date, const std::string &value)
{
if (!validateDate(date))
{
cout << "Error: bad input => " << date << endl;
return (false);
}
else if (validateValue(value) == 2)
{
cout << "Error: not a positive number." << endl;
return (false);
}
else if (validateValue(value) == 3)
{
cout << "Error: too large a number." << endl;
return (false);
}
return (true);
}
bool BitcoinExchange::validateDate(const std::string &date)
{
int maxDay = 31;
int year;
int month;
int day;
char dash;
bool bisiesto;
if (date.length() != 10 || date[4] != '-' || date[7] != '-')
return (false);
std::istringstream ss(date);
ss >> year >> dash >> month >> dash >> day;
bisiesto = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
if (year < 2008)
return (false);
if (month < 1 || month > 12)
return (false);
if (month == 2)
{
if (bisiesto)
maxDay = 29;
else
maxDay = 28;
}
if (day < 1 || day > maxDay)
return (false);
return (true);
}
int BitcoinExchange::validateValue(const std::string &value)
{
char *endptr;
double val = std::strtod(value.c_str(), &endptr);
if (*endptr != '\0')
return (1);
if (val < 0)
return (2);
else if (val > 1000)
return (3);
return (0);
}

View File

@@ -25,6 +25,10 @@ class BitcoinExchange
{
private:
std::map<std::string, double> data;
bool validateAll(const std::string &date, const std::string &value);
bool validateDate(const std::string &date);
int validateValue(const std::string &value);
public:
BitcoinExchange();
@@ -33,6 +37,7 @@ class BitcoinExchange
~BitcoinExchange();
void readDatabase(std::ifstream &db);
void execute(std::ifstream &db);
};
#endif