C++ 将字符转换为 ASCII?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15505375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:26:52  来源:igfitidea点击:

Converting a char to ASCII?

c++visual-studio-2010

提问by user2187476

I have tried lots of solutions to convert a char to Ascii. And all of them have got a problem.

我已经尝试了很多解决方案来将字符转换为 Ascii。他们都遇到了问题。

One solution was:

一种解决方案是:

char A;
int ValeurASCII = static_cast<int>(A);

But VS mentions that static_cast is an invalid type conversion!!!

但是 VS 提到 static_cast 是无效的类型转换!!!

PS: my A is always one of the special chars (and not numbers)

PS:我的 A 始终是特殊字符之一(而不是数字)

回答by Pete Becker

A charis an integral type. When you write

Achar是整数类型。当你写

char ch = 'A';

you're setting the value of chto whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A'these days, but that's not required. You're almost certainly using a system that uses ASCII.

您将 的值设置为ch编译器用来表示字符的任何数字'A'。这通常是'A'这些天的 ASCII 代码,但这不是必需的。您几乎可以肯定使用的是使用 ASCII 的系统。

Like any numeric type, you can initialize it with an ordinary number:

与任何数字类型一样,您可以使用普通数字对其进行初始化:

char ch = 13;

If you want do do arithmetic on a charvalue, just do it: ch = ch + 1;etc.

如果你想对一个char值进行算术运算,就这样做:ch = ch + 1;等等。

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display charvalues as characters rather than numbers. There are a couple of ways to do that.

但是,为了显示值,您必须绕过 iostreams 库中的假设,即您希望将char值显示为字符而不是数字。有几种方法可以做到这一点。

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

回答by Nik Bougalis

Uhm, what's wrong with this:

嗯,这有什么问题:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}

回答by tom

You can use chars as is as single byte integers.

您可以按原样使用字符作为单字节整数。