The other reviews have hit most of the important points, so I'll just provide a single line alternative that uses the C++11 std::regex_match
. That function looks like this:
bool wasInteger(const std::string &num) {
return std::regex_match(num, std::regex("[+-]?[0-9]+"));
}
With a regex this simple, I might not bother with a wrapper function.
Test your function
I also wrote (and encourage you to write) a simple test program:
#include <iostream>
#include <iomanip>
#include <string>
#include <regex>
bool wasInteger(const std::string &num) {
return std::regex_match(num, std::regex("[+-]?[0-9]+"));
}
struct Test {
std::string str;
bool expected;
};
static const std::string CSI{"\x1b["};
static const std::string RED{CSI + "31m"};
static const std::string GREEN{CSI + "32m"};
static const std::string RESET{CSI + "0m"};
int main() {
static const Test tests[]{
{"+", false},
{"-", false},
{"0", true},
{"3", true},
{"9", true},
{"a", false},
{"99a9", false},
{"9909", true},
{"", false},
{"-3.14", false},
{"+32768", true},
{"-32768", true},
};
static const std::string badgood[]{
RED + "[BAD] " + RESET,
GREEN + "[OK] "+ RESET
};
for (const auto &t : tests) {
auto result = wasInteger(t.str);
std::cout << badgood[result == t.expected]
<< std::boolalpha << "got " << result
<< ", expected " << t.expected
<< " from \"" << t.str << "\"\n";
}
}
Results
When I run the program I get the following output:
[OK] got false, expected false from "+"
[OK] got false, expected false from "-"
[OK] got true, expected true from "0"
[OK] got true, expected true from "3"
[OK] got true, expected true from "9"
[OK] got false, expected false from "a"
[OK] got false, expected false from "99a9"
[OK] got true, expected true from "9909"
[OK] got false, expected false from ""
[OK] got false, expected false from "-3.14"
[OK] got true, expected true from "+32768"
[OK] got true, expected true from "-32768"
+
character. \$\endgroup\$