将字符转换为ASCII? [英] Converting a char to ASCII?

查看:142
本文介绍了将字符转换为ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过很多解决方案来将字符转换为Ascii。

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

一个解决方案是:

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

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

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

PS:my A总是特殊字符之一(而不是数字)

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

推荐答案

code> char 是一个整数类型。

A char is an integral type. When you write

char ch = 'A';

您正在设置 ch 到你的编译器用来表示字符'A'的任何数字。这通常是'A'的ASCII代码,但这不是必需的。您几乎肯定会使用使用ASCII的系统。

you're setting the value of ch to 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.

像任何数字类型一样,您可以使用普通数字初始化它:

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

char ch = 13;

如果你想在 char value,只要这样: ch = ch + 1; 等。

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

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

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

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

这篇关于将字符转换为ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆