获取字符的十进制ASCII值

4

我需要获取字符的十进制ASCII值。到目前为止,使用以下方法可以打印它(避免负值)。

char x;
cout << dec << (int)x << endl;

问题出现在我想将 dec 值赋给一个 int 变量时,dec 不能在 cout 之外使用。有什么建议吗?请注意,(int) char 不起作用,因为我也会得到负值,而我想避免它们。
我已经尝试过使用 atoiunsigned int,但迄今为止没有成功。

2
cout << (int) x; not (int)char - Raindrop7
2
如果 x<0,它不是ASCII。 - aschepler
1
为什么要使用 << dec?我不知道为什么,但我有一个大小为1024的char数组。如果我不加上<<dec,我会得到负值。我正在使用VB2015。 - Capie
2
“十进制 ASCII 值” 指的确切含义是什么? ASCII 码不是十进制、十六进制或二进制,它们是 整数 - n. m.
1
@Capie 十进制和十六进制是写下同一个数字的不同方式。 - n. m.
显示剩余9条评论
4个回答

5

char类型的对象转换为unsigned char类型的对象就足够了。例如:

char c = CHAR_MIN; 

int x = ( unsigned char )c;

或者

int x = static_cast<unsigned char>( c );

1

这取决于编译器的实现,一些编译器将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;
}

0
在C++中,使用static_cast<int>(someCharValue)将有符号字符(和无符号字符)值转换为整数 - 但这不是一个有意义的操作,因为char本身就是一种整数类型。
如果您想要一个十进制字符串,则使用C++11的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。


明天会检查并告诉你。 - Capie

0

你可以通过显式转换或隐式转换将字符转换为整数:

int a = 'a'; // implicit conversion
cout << a << endl; // 97

int A = (int)'A'; explicit conversion
cout << a << endl; // 65

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接