0

How is it possible to check if a String is a valid number. The number can be both an int or a double like:

String^ ValidInt = "5";
String^ ValidDouble = "5.01";
2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Darth Vader
0

The normal way to do this is to use a stringstream.
Now you have to be VERY VERY careful, with this.
The reason is that if you do

double Res;
std::string A="3.4e5x"
std::stringstream IX(A);
A>>Res;

This cose will happily set Res equal to 34000. Which is not correct.
So Try this:

// This function returns true if the number is valid
// and sets Res to the correct number
template<typename T>
bool 
convert(const std::string& A,T& Res)
{
 std::istringstream iss(A);
 iss>>Res;
 return (iss.fail() || iss.tellg()!=A.length()) ?
   false : true;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.