views:

171

answers:

5

Let's say I want to look at the character at position 10 in a string s.

s.at(10);

What would be the easiest way to know if this is a number?

+8  A: 

Use isdigit

std::string s("mystring is the best");
if ( isdigit(s.at(10)) ){
    //the char at position 10 is a digit
}
Yacoby
fails for the following digits: ४, ୬, ௧, ໙
Bill
@Bill Sure, but the example was based on the assumption that the requirement was for ascii digits. The page I linked to explained the solution if the programmer required locale specific digits and I can't second guess the programmers requirements.
Yacoby
@Yacoby: I understand your assumptions, I just didn't see anything in the original question to justify them.
Bill
+1  A: 

if(isdigit(s.at(10)) { }

nos
+4  A: 

The following will tell you:

isdigit( s.at( 10 ) )

will resolve to 'true' if the character at position 10 is a digit.

You'll need to include < ctype >.

Andrew
I didn't need to include ctype and it still worked.
Phenom
In C++, implementations may set up their headers such that one header includes another. `std::string` required `<string>` which may very well have brought in `<ctype>` _on your implementation_. That's coincidence; you can't rely on that.
MSalters
+1  A: 

Another way is to check the ASCII value of that character

if ( s.at(10) >= '0' && s.at(10) <= '9' )
  // it's a digit
IVlad
This fails for digits such as ४, ୬, ௧, ໙ . std::isdigit is a better choice for real-world applications: http://www.cplusplus.com/reference/std/locale/isdigit/
Bill
+2  A: 

The other answers assume you only care about the following characters: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. If you are writing software that might operate on locales that use other numeral systems, then you'll want to use the newer std::isdigit located in <locale>: http://www.cplusplus.com/reference/std/locale/isdigit/

Then you could recognize the following digits as digits: ४, ੬, ൦, ௫, ๓, ໒

Bill