1

I would like to know how to test if a char is a number. An int has been converted to char and later on I want to see if this char is a number.

int num = 2;
char number = '2';
char num2 = (char)num;
cout << "Non comverted: " << number << " " << num2 << endl;
cout << "comverted: " << static_cast<int>(number) << " " << static_cast<int>(num2) << endl;
if (isdigit(number))
  cout << "number" << endl;
else if (isdigit(num2))
  cout << "num2" << endl;
else cout << "none" << endl;

when I run this the second if should also be able to relate to true.

The reason why I want to be able to do this is because I store a lot of different values into a char array and would later like to know when something is a number or not.

Thanx a lot

3 Answers 3

0

You aren't actually converting num to a number. Your line 3 basically results in:

char num2 = (char)2;

The ASCII character with decimal value 2 is not a digit. In fact, it is not printable. The easiest way to convert a single digit integer to its printable char is to add '0' to it:

char num2 = '0' + num;

The reason for this is that the character 0 is the first digit in the ASCII table, directly followed by 1, 2, 3, etc...

Edit

As Christian Hackl points out in the comments, c++ does not require an implementation to use ASCII, although it is guaranteed that the digits 0 through 9 are represented by contiguous integer values.

2
  • C++ does not require an implementation to use ASCII, although it does guarantee the range from 0 to 9 to be contiguous. Oct 10, 2014 at 14:47
  • Thanx I just realised that what I wanted to do was not going to work anyway Oct 14, 2014 at 16:30
0

To translate single digits from int to ascii/utf8 characters there is a very simple conversion:

char num2 = static_cast<char>('0' + num);

0

This:

char num2 = (char)num;

Does not make sense. You're casting a 2 to a char which will give you ASCII code for STX, a special character (http://www.asciitable.com/).

You probably want this:

char num2 = '0' + num;

What that does is give you a character counted from ASCII '0', so it will work up to 9, after which you will get other characters as seen in the ASCII table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.