I wrote the following code to check whether the input(answer3) is a number or string, if it is not a number it should return \"Enter Numbers Only\" but it returns the same e
You can use regex to do this:
#include
bool isNumber(std::string x){
std::regex e ("^-?\\d+");
if (std::regex_match (x,e)) return true;
else return false;}
If you want to make isNumber() a generic function which can take any type of input:
#include
#include
template
bool isNumber(T x){
std::string s;
std::regex e ("^-?\\d+");
std::stringstream ss;
ss << x;
ss >>s;
if (std::regex_match (s,e)) return true;
else return false;}
The above isNumber() function checks for integer only, double or float value with precision (which contains dot .) will not return true.
If you want precision too, then change the regex line to:
std::regex e ("^-?\\d*\\.?\\d+");
If you want a more efficient solution, see this one.