neuromancer
neuromancer

Reputation: 55479

How to find out if a character in a string is an integer

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?

Upvotes: 10

Views: 42417

Answers (5)

nos
nos

Reputation: 229058

Use isdigit:

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

Upvotes: 3

Yacoby
Yacoby

Reputation: 55445

Use isdigit

std::string s("mystring is the best");
if ( isdigit(s.at(10)) ){
    //the char at position 10 is a digit
}

You will need

#include <ctype.h>

to ensure isdigit is available regardless of implementation of the standard library.

Upvotes: 21

Bill
Bill

Reputation: 14685

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: ४, ੬, ൦, ௫, ๓, ໒

Upvotes: 9

IVlad
IVlad

Reputation: 43477

Another way is to check the ASCII value of that character

if ( s.at(10) >= '0' && s.at(10) <= '9' )
  // it's a digit

Upvotes: 4

Andrew
Andrew

Reputation: 12009

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 >.

Upvotes: 5

Related Questions