我需要获取字符的十进制ASCII值。到目前为止,使用以下方法可以打印它(避免负值)。
char x;
cout << dec << (int)x << endl;
问题出现在我想将
dec
值赋给一个 int
变量时,dec
不能在 cout
之外使用。有什么建议吗?请注意,(int) char
不起作用,因为我也会得到负值,而我想避免它们。我已经尝试过使用
atoi
和 unsigned int
,但迄今为止没有成功。我需要获取字符的十进制ASCII值。到目前为止,使用以下方法可以打印它(避免负值)。
char x;
cout << dec << (int)x << endl;
dec
值赋给一个 int
变量时,dec
不能在 cout
之外使用。有什么建议吗?请注意,(int) char
不起作用,因为我也会得到负值,而我想避免它们。atoi
和 unsigned int
,但迄今为止没有成功。将char
类型的对象转换为unsigned char
类型的对象就足够了。例如:
char c = CHAR_MIN;
int x = ( unsigned char )c;
或者
int x = static_cast<unsigned char>( c );
这取决于编译器的实现,一些编译器将char实现为无符号,并允许扩展的ASCII字符(http://www.ascii-code.com/)。下面两个链接具有相同的代码,但只有一个可以工作: http://ideone.com/72Iiaz // 使用gcc c++ 4.*且无法编译 http://ideone.com/hbmBK6 // 使用c++ 14
#include<iostream>
using namespace std;
int main(){
char ch = 'x';
int num = ch;
cout<<ch<<" => " << num << endl;
ch = 'µ'; // should now have an extended ascii character
num = ch;
cout<<ch<<" => " << num << endl;
cout<<" using unsigned "<< (unsigned int) 'µ';
return 0;
}
static_cast<int>(someCharValue)
将有符号字符(和无符号字符)值转换为整数 - 但这不是一个有意义的操作,因为char
本身就是一种整数类型。std::to_string
函数:#include <string>
using namespace std;
char someChar = 'A';
int someCharAsInteger = static_cast<int>( someChar ); // this step is unnecessary, but it's to demonstrate that they're all just integers.
string someCharsNumericIntegerValueAsDecimalString1 = to_string( someChar ); // as there is no `to_string(char)` implicit upsizing to `int` will occur.
string someCharsNumericIntegerValueAsDecimalString2 = to_string( someCharAsInteger );
cout << someCharsNumericIntegerValueAsDecimalString1 << endl;
cout << someCharsNumericIntegerValueAsDecimalString2 << endl;
这将输出:
65
65
假设您的系统是ASCII。
你可以通过显式转换或隐式转换将字符转换为整数:
int a = 'a'; // implicit conversion
cout << a << endl; // 97
int A = (int)'A'; explicit conversion
cout << a << endl; // 65
cout << (int) x;
not(int)char
- Raindrop7x<0
,它不是ASCII。 - aschepler<< dec
?我不知道为什么,但我有一个大小为1024的char
数组。如果我不加上<<dec
,我会得到负值。我正在使用VB2015。 - Capie