如何检查字符常量是否符合ASCII? [英] How do I check whether character constants conform to ASCII?

查看:254
本文介绍了如何检查字符常量是否符合ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A comment on an earlier version of this answer of mine alerted me to the fact that I can't assume that 'A', 'B', 'C' etc. have successive numeric values. I had sort of assumed the C or C++ language standards guarantee that this is the case.

那么,我应该如何确定连续字母字符的值本身是否是连续的?或者更确切地说,如何确定单引号中可以表达的字符常量是否具有用于数字值的ASCII代码?

So, how should I determine whether consecutive letter characters' values are themselves consecutive? Or rather, how can I determine whether the character constants I can express within single quotes have their ASCII codes for a numeric value?

我在问如何在C和C ++中做到这一点.显然,C方式也可以在C ++中使用,但是如果有C ++ ish的工具可以做到这一点,我也会对此感兴趣.另外,我在问最新的相关标准(C11,C ++ 17).

I'm asking how to do this both in C and in C++. Obviously the C way would work in C++ also, but if there's a C++ish facility for doing this I'm interested in that as well. Also, I'm asking about the newest relevant standards (C11, C++17).

推荐答案

您可以使用预处理器检查特定字符是否映射到字符集:

You can use the preprocessor to check if a particular character maps to the charset:

#include <iostream>
using namespace std;

int main() {
    #if ('A' == 65 && 'Z' - 'A' == 25)
    std::cout << "ASCII" << std::endl;
    #else
    std::cout << "Other charset" << std::endl;
    #endif
    return 0;
}

缺点是,您需要事先知道映射的值.

The drawback is, you need to know the mapped values in advance.

保证数字字符'0'-'9'以连续顺序BTW出现.

The numeric chars '0' - '9' are guaranteed to appear in consecutive order BTW.

这篇关于如何检查字符常量是否符合ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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