Skip to content

Instantly share code, notes, and snippets.

@missirol
Last active March 5, 2023 10:09
Show Gist options
  • Save missirol/81935e0675250905ac4f30e9806b3255 to your computer and use it in GitHub Desktop.
Save missirol/81935e0675250905ac4f30e9806b3255 to your computer and use it in GitHub Desktop.
#include <charconv>
#include <exception>
#include <iostream>
#include <regex>
#include <string>
// Pre PR
bool isNumber(const std::string &str) {
static const std::regex re("^[+-]?(\\d+\\.?|\\d*\\.\\d*)$");
return std::regex_match(str.c_str(), re);
}
double toNumber(const std::string &str) { return atof(str.c_str()); }
// PR 40956
bool toNumber(std::string const& str, double &result) {
if (str.empty()) {
return false;
}
const char *first = str.c_str();
const char *last = first + str.size();
if (*first == '+') {
++first;
}
const auto [ptr, ec] = std::from_chars(first, last, result);
return ec == std::errc();// and ptr == last;
}
// main
int main (int argc, char** argv) {
if (argc != 2) {
std::cout << "One command-line argument required" << std::endl;
return 1;
}
std::string const str = argv[1];
std::cout << "String: '" << str << "'" << std::endl;
{
std::cout << "=== Pre PR" << std::endl;
if (isNumber(str)) {
std::cout << "YES, is number " << toNumber(str) << std::endl;
}
else {
std::cout << "NO, is no number" << std::endl;
}
std::cout << "=============" << std::endl;
}
{
std::cout << "=== PR 40915" << std::endl;
try {
double const number = std::stof(str);
std::cout << "YES, is number " << number << std::endl;
}
catch (std::exception const& ex) {
std::cout << "NO, is no number (" << ex.what() << ")" << std::endl;
}
std::cout << "=============" << std::endl;
}
{
std::cout << "=== PR 40956" << std::endl;
double number{};
if (toNumber(str, number)) {
std::cout << "YES, is number " << number << std::endl;
}
else {
std::cout << "NO, is no number" << std::endl;
}
std::cout << "=============" << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment