这是这个问题的扩展问题:Is std::string suppose to have only Ascii characters
我想构建一个简单的控制台应用程序,它将用户的输入作为字符集。这些字符包括0->9
数字和 a->z
字母。
我正在处理假设它是 Ascii 的输入。例如,我使用类似:static_cast<unsigned int>(my_char - '0')
得到号码 unsigned int
.
如何使此代码跨平台?如何知道我希望输入始终为 Ascii?或者我错过了很多概念和static_cast<unsigned int>(my_char - '0')
只是一个坏方法吗?
附注在 Ascii 中(至少)数字是有顺序的。但是,在其他编码中,我不知道是否有。 (我很确定它们是,但不能保证,对吧?)
最佳答案
How can force the user/OS to input an Ascii string
不能,除非您让用户指定此类 ASCII 输入的数值。
这完全取决于用于服务 std::cin
的终端实现如何将 0
等击键转换为特定数字,以及您的工具链期望与该数字匹配的内容其内在翻译为'0'
。
您根本不应该期望显式地使用 ASCII 值(例如使用魔数(Magic Number)),而应该使用 char
文字来提供可移植代码。 my_char - '0'
将产生实际数字值的假设对于所有字符集都是成立的。 C++ 标准在 [lex.charset]/3 中指出
The basic execution character set and the basic execution wide-character set shall each contain all the members of the basic source character set, plus control characters representing alert, backspace, and carriage return, plus a null character (respectively, null wide character), whose representation has all zero bits. For each basic execution character set, the values of the members shall be non-negative and distinct from one another. In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.[...]
强调我的
关于c++ - 如何强制用户/操作系统输入 Ascii 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37953843/