[英]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值已转换为char,稍后我要查看此char是否为数字。
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. 当我运行此命令时,第二个if也应该能够与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. 之所以要执行此操作,是因为我将许多不同的值存储到char数组中,并且稍后想知道什么时候是数字。
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/ ). 您正在将2强制转换为char,这将为您提供STX的ASCII码,一个特殊字符( 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. 这样做是给您一个从ASCII'0'开始计数的字符,因此它将最多工作9个字符,之后您将获得其他字符,如ASCII表所示。
You aren't actually converting num
to a number. 您实际上并没有将num
转换为数字。 Your line 3 basically results in: 您的第3行基本上导致:
char num2 = (char)2;
The ASCII character with decimal value 2 is not a digit. 十进制值为2的ASCII字符不是数字。 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
的最简单方法是在其上添加'0'
:
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... 这是因为字符0
是ASCII表中的第一位数字,直接后跟1,2,3等。
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. 正如克里斯蒂安·哈克在评论指出, C ++不要求使用ASCII一个实现 ,虽然它保证了数字0
至9
是由连续的整数值来表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.