我的灵感来自this answer .
我想到的一种方法是结合使用static_assert
(C11-onwards)和assert
。
基本上,一个带有一堆的 ascii.h
文件
static_assert(' ' == 32);
static_assert('!' == 33);
// ...
语句然后是函数
static void assert_runtime_ascii(void) {
assert(' ' == 32);
assert('!' == 33);
// ...
}
在main
中执行。
这太冗长了(200 多行),因此不切实际,所以我只是评论一下
// NOTE: this program expects ASCII both at run-time and compile-time.
完成。
有更好的方法吗?
我在标准中找不到类似 __STDC_IEC_559__
的 ASCII 的 #define
。
有更好的方法吗?
最佳答案
best way to guarantee ASCII both at compile-time and run-time?
听起来OP想知道如何检测执行字符集编码和用户I/O编码。
在编译时或运行时,要检测 ASCII,请使用一系列 _Static_asserts
或 asserts
(example code)对于大多数 128 ASCII字符,属于 C 语言执行字符集的一部分。 C11 §5.2.1 3
A to Z
a to z
0 to 9
! " # % & ’ ( ) * + , - . / : ; < = > ? [ \ ] ^ _ { | } ~
space character,
and control characters representing horizontal tab, vertical tab, and form feed.
some way of indicating the end of each line of text
请注意,像“$、@、`”这样的字符不属于执行字符集,因此“如果没有相应的成员,则会将其转换为实现定义的成员,而不是空(宽)字符”适用。
<小时/>要检测用户输入/输出的编码,除了要求用户输入引用文本并对其进行代码检查之外,我没有找到其他解决方案。
关于c - 在编译时和运行时保证 ASCII 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60122693/