c++ - 如何强制用户/操作系统输入 Ascii 字符串

标签 c++ string c++11 ascii

这是这个问题的扩展问题: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/

相关文章:

c++ - Qt 5.0.1 : Application will not execute outside of Qt creator

php - 如何在 MySQL 中存储包含 nbsp 和 br(换行符)s 的大字符串 moSTLy?

c++ - 设置与具有字符串成员的结构 vector

c++ - 赋值运算符是否应该观察被赋值对象的右值?

c++ - 将 map 与 vector 和缓存影响结合使用

C++ 算法按以下顺序切换数组的顺序 : [Last, First, Last - 1, First + 1...]

c++ - 影响数字比较的双粒度c++

c++ - 取消引用映射迭代器时返回对临时对象的引用

c++ - QT套接字读取丢失字节

c - 在 C 中围绕元音旋转单词