C++: Determine if a String Is Numeric

Bjarne-stroustrup
 

Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.

Using stringstream:

#include <sstream> // for istringstream

using namespace std;

bool isNumeric( const char* pszInput, int nNumberBase )
{
	istringstream iss( pszInput );

	if ( nNumberBase == 10 )
	{
		double dTestSink;
		iss >> dTestSink;
	}
	else if ( nNumberBase == 8 || nNumberBase == 16 )
	{
		int nTestSink;
		iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
	}
	else
	return false;

	// was any input successfully consumed/converted?
	if ( ! iss )
	return false;

	// was all the input successfully consumed/converted?
	return ( iss.rdbuf()->in_avail() == 0 );
}

Using find:

bool isNumeric( const char* pszInput, int nNumberBase )
{
	string base = "0123456789ABCDEF";
	string input = pszInput;

	return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
}

Using all_of (requires C++11):

bool isNumeric(const std::string& input) {
	return std::all_of(input.begin(), input.end(), ::isdigit);
}

SOURCE

Content is available under GNU Free Documentation License 1.2.

Subscribe to TFE Times

Enter your email address to become a member of TFE Times today!