Files
42_INT_09_piscine_cpp/d06/ex00/srcs/checkDouble.cpp
2022-03-08 16:51:12 +01:00

66 lines
1.7 KiB
C++

#include "convert.h"
void fromDouble(double value) {
// char
std::cout << std::setw(7) << std::left << "char";
if (value < 0 || value > std::numeric_limits<char>::max())
std::cout << B_RED << "impossible" << RESET "\n";
else if (!isprint(value))
std::cout << B_RED << "non displayable" << RESET "\n";
else
std::cout << B_CYAN << static_cast<char>(value) << RESET "\n";
// int
std::cout << std::setw(7) << std::left << "int";
if (value < std::numeric_limits<int>::min()
|| value > std::numeric_limits<int>::max() )
std::cout << B_RED << "impossible" << RESET "\n";
else
std::cout << B_CYAN << static_cast<int>(value) << RESET "\n";
// float
std::cout << std::setw(7) << std::left << "float";
if (value < std::numeric_limits<float>::min()
|| value > std::numeric_limits<float>::max() )
std::cout << B_RED << "impossible" << RESET "\n";
else
std::cout << B_CYAN << static_cast<double>(value) << RESET "\n";
}
bool isDouble(std::string str) {
size_t l;
if (str[0] == '+' || str[0] == '-')
str.erase(str.begin());
if (str.length() == 0)
return false;
if (!str.compare("inf") || !str.compare("nan"))
return true;
l = str.find_first_not_of("0123456789");
if (l == std::string::npos || str[l] != '.' || l > DOUBLE_MAX_LENGTH)
return false;
if (str.find_first_not_of("0123456789", l + 1) != std::string::npos)
return false;
if (l < DOUBLE_MAX_LENGTH)
return true;
if (str.compare(0, l, MAX_DOUBLE) > 0)
return false;
return true;
}
bool checkDouble(std::string str) {
double d;
if (!isDouble(str))
return false;
std::istringstream(str) >> d;
std::cout << B_CYAN << d << B_YELLOW " double" RESET "\n";
fromDouble(d);
return true;
}