Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active August 26, 2020 01:43
Show Gist options
  • Save komasaru/74a8c82430826eb58a257cff67c18363 to your computer and use it in GitHub Desktop.
Save komasaru/74a8c82430826eb58a257cff67c18363 to your computer and use it in GitHub Desktop.
C++ source code to judge if a string is an integer.
/***************************************************************
Check integer
$ g++ -std=c++17 -Wall -O2 --pedantic-errors -o is_integer is_integer.cpp
DATE AUTHOR VERSION
2020.08.21 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_int(std::string s) {
std::smatch m;
std::regex re("^[+-]?\\d+$");
try {
if (!std::regex_search(s, m, re))
return false;
} catch (std::regex_error& e) {
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_int(buf))
std::cout << "NOT ";
std::cout << "INTEGER\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