如何强制用户/ OS输入Ascii字符串 [英] How can force the user/OS to input an Ascii string

查看:131
本文介绍了如何强制用户/ OS输入Ascii字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此问题的扩展问题:是std ::字符串假设只有Ascii字符

This is an extended question of this one: Is std::string suppose to have only Ascii characters

我想构建一个简单的控制台应用程序,将来自用户的输入作为一组字符。这些字符包括 0-> 9 数字和 a-> z 字母。

I want to build a simple console application that take an input from the user as set of characters. Those characters include 0->9 digits and a->z letters.

我处理的输入假设它是一个Ascii。例如,我使用类似: static_cast< unsigned int>(my_char - '0')得到 unsigned int

I am dealing with input supposing that it is an Ascii. For example, I am using something like : static_cast<unsigned int>(my_char - '0') to get the number as unsigned int.

如何使此代码跨平台?怎么能告诉我,我想要输入总是Ascii?或者我错过了很多的概念, static_cast< unsigned int>(my_char - '0')只是一个坏的方式吗?

How can I make this code cross-platform? How can tell that I want the input to be Ascii always? Or I have missed a lot of concepts and static_cast<unsigned int>(my_char - '0') is just a bad way?

PS在Ascii(至少)数字有顺序。但是,在其他编码,我不知道他们是否有。 (我确定他们是,但没有保证,对吗?)

P.S. In Ascii (at least) digits have sequenced order. However, in others encoding, I do not know if they have. (I am pretty sure that they are but there is no guarantee, right?)

推荐答案


可以强制用户/ OS输入Ascii字符串

How can force the user/OS to input an Ascii string

除非你让用户指定这种ASCII输入的数字值。

You cannot, unless you let the user specify the numeric values of such ASCII input.

这取决于终端实现如何服务 std :: cin $ c> 0 到一个特定的数字,以及你的工具链希望匹配那个数字与它的固有翻译'0'

It all depends how the terminal implementation used to serve std::cin translates key strokes like 0 to a specific number, and what your toolchain expects to match that number with it's intrinsic translation for '0'.

您不应该明确地期望ASCII值(例如使用魔术数字),但是 char 文字提供可移植代码。假设 my_char - '0'将导致所有字符集的实际位数值为真。 C ++标准在[lex.charset] / 3中规定

You simply shouldn't expect ASCII values explicitly (e.g. using magic numbers), but char literals to provide portable code. The assumption that my_char - '0' will result in the actual digits value is true for all character sets. The C++ standard states in [lex.charset]/3 that


基本执行字符集和基本执行宽字符集包含基本源字符集的所有成员,以及表示警报,退格和回车的控制字符,以及一个空字符(分别为空宽字符),其表示全部为零位。对于每个基本执行字符集,成员的值应是非负的并且彼此不同。 在源和执行基本字符集中,上述十进制数字列表中的每个字符在0之后的值应大于前一个字符的值。 [...]

强调我

这篇关于如何强制用户/ OS输入Ascii字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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