Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active August 26, 2020 01:44
Show Gist options
  • Save komasaru/6251f48d728f07496cfac69f4cff4c49 to your computer and use it in GitHub Desktop.
Save komasaru/6251f48d728f07496cfac69f4cff4c49 to your computer and use it in GitHub Desktop.
C++ source code to judge if a string is an real number.
/***************************************************************
Check real number
$ g++ -std=c++17 -Wall -O2 --pedantic-errors -o is_real is_real.cpp
DATE AUTHOR VERSION
2020.08.24 mk-mode.com 1.00 新規作成
Copyright(C) 2020 mk-mode.com All Rights Reserved.
***************************************************************/
#include <iostream> // for cout
#include <regex> // for regex etc.
namespace funcs {
bool is_real(std::string s) {
std::smatch m;
std::regex re("^[+-]?(\\d+\\.\\d*|\\.\\d+)$");
try {
if (!std::regex_search(s, m, re))
return false;
} catch (std::regex_error& e) {
//std::cout << "[EXCEPTION] Regex error! ("
// << e.what() << ")" << std::endl;
return false;
}
return true;
}
}
int main(int argc, char* argv[]) {
std::string buf;
try {
while (true) {
std::cout << "n? ";
getline(std::cin, buf);
if (buf.empty())
break;
std::cout << buf << ": ";
if (!funcs::is_real(buf))
std::cout << "NOT ";
std::cout << "REAL NUMBER\n---" << std::endl;
}
} catch (...) {
std::cerr << "EXCEPTION!" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment