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

Charl Meyers
  • 115
  • 1
  • 8

3 Answers3

0

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

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

Oliver
  • 785
  • 1
  • 7
  • 14
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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
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.

Community
  • 1
  • 1
Bart van Nierop
  • 4,130
  • 2
  • 28
  • 32