Skip to content

Instantly share code, notes, and snippets.

@komasaru

komasaru/is_integer.cpp

Last active Aug 26, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.