I\'ve had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am r
to check if a string is a number integer or floating point or so you could use :
#include <sstream>
bool isNumber(string str) {
double d;
istringstream is(str);
is >> d;
return !is.fail() && is.eof();
}
Here is a solution for checking positive integers:
bool isPositiveInteger(const std::string& s)
{
return !s.empty() &&
(std::count_if(s.begin(), s.end(), std::isdigit) == s.size());
}
As it was revealed to me in an answer to my related question, I feel you should use boost::conversion::try_lexical_convert
Yet another answer, that uses stold
(though you could also use stof
/stod
if you don't require the precision).
bool isNumeric(const std::string& string)
{
std::size_t pos;
long double value = 0.0;
try
{
value = std::stold(string, &pos);
}
catch(std::invalid_argument&)
{
return false;
}
catch(std::out_of_range&)
{
return false;
}
return pos == string.size() && !std::isnan(value);
}
include <string>
For Validating Doubles:
bool validateDouble(const std::string & input) {
int decimals = std::count(input.begin(), input.end(), '.'); // The number of decimals in the string
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == decimals + negativeSigns) // Consists of only decimals and negatives or is empty
return false;
else if (1 < decimals || 1 < negativeSigns) // More than 1 decimal or negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-.0123456789") != input.size()) // The string contains a character that isn't in "-.0123456789"
return false;
return true;
}
For Validating Ints (With Negatives)
bool validateInt(const std::string & input) {
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == negativeSigns) // Consists of only negatives or is empty
return false;
else if (1 < negativeSigns) // More than 1 negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-0123456789") != input.size()) // The string contains a character that isn't in "-0123456789"
return false;
return true;
}
For Validating Unsigned Ints
bool validateUnsignedInt(const std::string & input) {
return (input.size() != 0 && strspn(input.c_str(), "0123456789") == input.size()); // The string is not empty and contains characters only in "0123456789"
}
We may use a stringstream class.
bool isNumeric(string str)
{
stringstream stream;
double number;
stream<<str;
stream>>number;
return stream.eof();
}