简体   繁体   中英

Test converted int to char if it is number c++

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

要将整数从int转换为ascii / utf8字符,有一个非常简单的转换:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM