if string is number only

ok, i been searching after this but with no good result
i would like to se if a string contains numbers only
i tried searching on this site but i found nothing good to be used

im totally new to c++ (begun today), however i do have experience with lua
This is an untested idea, but you could cast each char in the string to an int and use an IF statement to check if it's less than 10. For example:

1
2
3
4
5
6
7
8
string str = "3257fg";
for(int i = 0;i < (strlen(str) - 1);i++) {
    if((int)str[i] < 10) {
        // it is a number, so do some code
    } else {
        // it is not a number, do something else
    }
}


The reason this works is because when you cast a char to an int, the resulting value is the ASCII value of the character. For example, if you cast "a" to an integer, the resulting value would be 97. The last ASCII digit is 9, so if the ASCII value is less than 10, it's a digit.
Last edited on
'strlen' : cannot convert parameter 1 from 'std::string' to 'const char *'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Show your code...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> // http://www.cplusplus.com/reference/iostream/iostream/
#include <string> // http://www.cplusplus.com/reference/string/string/
#include <fstream> // http://www.cplusplus.com/reference/iostream/fstream/
#include <cstdlib> // http://www.cplusplus.com/reference/clibrary/cstdlib/


using namespace std;

bool is_number(string str)
	{
	for(int i = 0;i < (strlen(str) - 1);i++) {
		if((int)str[i] < 10) {
			return true;
		} else {
			return false;
		}
	}
	}


this is the header file
You are passing std::string to strlen which takes c-style strings.
Instead of strlen, try using the length() method:
 
str.length();


Alternatively, if you insist using strlen, do:
 
strlen(str.c_str());
Last edited on
your talking to packetpirat right?
btw, yeah i already figured that out, but it still doesent work
If you want to see if every character in a string is a digit then loop through the string and check each character with isdigit().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cctype>
#include <string>

...

string s;

bool has_only_digits = true;
for (size_t n = 0; n < s.length(); n++)
  {
  if (!isdigit( s[ n ] ))
    {
    has_only_digits = false;
    break;
    }
  }

You can also use the string's find_first_not_of() method:

1
2
3
4
5
6
7
#include <string>

...

string s;

bool has_only_digits = (s.find_first_not_of( "0123456789" ) == string::npos);

Hope this helps.
Topic archived. No new replies allowed.