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";

Recommended Answers

All 2 Replies

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);

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>
convert(const std::string& A,T& Res)
 std::istringstream iss(A);
 return ( || iss.tellg()!=A.length()) ?
   false : true;

I will be careful, I will check your code.

Great help, thank you!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.