# How to judge if a string is a number?

• ### Question

• Now i want to judge if a string is a number, for example string "111234" is a number, but string "[12345]" is not a number, how to realize it ? is there function to be used in std or boost?

thks

Thursday, October 26, 2006 1:52 AM

• Those functions will give you 0 as the result value, so giving these doesn't answer the question.

Use isdigit() on each of the characters in the string.

Thursday, October 26, 2006 3:54 AM
•

You can use a string stream to do this:

Example with a char array

#include <iostream>
#include <sstream>

using namespace std;
int main(int argc, char* argv[])
{
char str[ 6 ]  = "100.5";
stringstream ss(str);
double d;
ss>>d;
cout<<ss.good()<<"\n";
return 0;
}

Example with a std::string

int main(int argc, char* argv[])
{
string str  = "100.5";
stringstream ss(str);
double d;
ss>>d;
cout<<ss.good()<<"\n";
return 0;
}

Regards

Sahir Shah

Thursday, October 26, 2006 4:45 AM

### All replies

• CRT provides the following set of function to convert a string (char *) to a integer

atoi, _atoi_l, _wtoi, _wtoi_l

Please check the help on these api's for details

Thursday, October 26, 2006 2:03 AM
• Those functions will give you 0 as the result value, so giving these doesn't answer the question.

Use isdigit() on each of the characters in the string.

Thursday, October 26, 2006 3:54 AM
•

You can use a string stream to do this:

Example with a char array

#include <iostream>
#include <sstream>

using namespace std;
int main(int argc, char* argv[])
{
char str[ 6 ]  = "100.5";
stringstream ss(str);
double d;
ss>>d;
cout<<ss.good()<<"\n";
return 0;
}

Example with a std::string

int main(int argc, char* argv[])
{
string str  = "100.5";
stringstream ss(str);
double d;
ss>>d;
cout<<ss.good()<<"\n";
return 0;
}

Regards

Sahir Shah

Thursday, October 26, 2006 4:45 AM