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
I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with
-?[0-9]+([\.][0-9]+)?
would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.
Other variations:
[0-9]+([\.][0-9]+)?
(only positive)
-?[0-9]+
(only integer)
[0-9]+
(only positive integer)
The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
Or if you want to do it the C++11 way:
bool is_number(const std::string& s)
{
return !s.empty() && std::find_if(s.begin(),
s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
}
As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.
I just wanted to throw in this idea that uses iteration but some other code does that iteration:
#include <string.h>
bool is_number(const std::string& s)
{
return( strspn( s.c_str(), "-.0123456789" ) == s.size() );
}
It's not robust like it should be when checking for a decimal point or minus sign since it allows there to be more than one of each and in any location. The good thing is that it's a single line of code and doesn't require a third-party library.
Take out the '.' and '-' if positive integers are all that are allowed.
Try this:
bool checkDigit(string str)
{
int n=str.length();
for(int i=0; i < n ; i++)
{
if(str[i]<'0' || str[i]>'9')
return false;
}
return true;
}
Could you simply use sscanf's return code to determine if it's an int?
bool is_number(const std::string& s)
{
int value;
int result = sscanf(valueStr.c_str(), "%d", &value);
return (result != EOF && readResult != 0);
}
The simplest I can think of in c++
bool isNumber(string s) {
if(s.size()==0) return false;
for(int i=0;i<s.size();i++) {
if((s[i]>='0' && s[i]<='9')==false) {
return false;
}
}
return true;
}
Working code sample: https://ideone.com/nRX51Y