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

62 lines
1.6 KiB
C++

#include "convert.h"
void fromFloat(float 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";
// double
std::cout << std::setw(7) << std::left << "double";
std::cout << B_CYAN << static_cast<double>(value) << RESET "\n";
}
bool isFloat(std::string str) {
size_t l;
size_t l2;
if (str[0] == '+' || str[0] == '-')
str.erase(str.begin());
if (str.length() == 0)
return false;
if (!str.compare("inff") || !str.compare("nanf"))
return true;
l = str.find_first_not_of("0123456789");
if (l == std::string::npos || str[l] != '.' || l > FLOAT_MAX_LENGTH)
return false;
l2 = str.find_first_not_of("0123456789", l + 1);
if (l2 == std::string::npos || l2 != str.length() - 1 || str[l2] != 'f')
return false;
if (l < FLOAT_MAX_LENGTH)
return true;
if (str.compare(0, l, MAX_FLOAT) > 0)
return false;
return true;
}
bool checkFloat(std::string str) {
float f;
if (!isFloat(str))
return false;
std::istringstream(str) >> f;
std::cout << B_CYAN << f << B_YELLOW " float" RESET "\n";
fromFloat(f);
return true;
}