简体   繁体   English

C++ 字符减法

[英]C++ char subtraction

So I realize that assuming ascii encoding can get you in trouble, but I'm never really sure how much trouble you can have subtracting characters.所以我意识到假设 ascii 编码会给你带来麻烦,但我从来不确定你在减去字符时会遇到多少麻烦。 I'd like to know what relatively common scenarios can cause any of the following to evaluate to false.我想知道哪些相对常见的情况会导致以下任何一项评估为假。

Given:鉴于:

std::string test = "B";
char m = 'M';

A) (m-'A')==12 A) (m-'A')==12

B) (test[0]-'D') == -2 B) (test[0]-'D') == -2

Also, does the answer change for lowercase values (changing the 77 to 109 ofc)?此外,小写值的答案是否会发生变化(将77更改为109 ofc)?

Edit: Digit subtraction answers this question for char digits, by saying the standard says '2'-'0'==2 must hold for all digits 0-9 , but I want to know if it holds for az and AZ , which section 2.3 of the standard is unclear on in my reading.编辑: 数字减法回答了字符数字的这个问题,说标准说'2'-'0'==2 must hold for all numbers 0-9 ,但我想知道它是否适用于azAZ ,哪个部分2.3的标准在我的阅读中不清楚。

Edit 2: Removed ASCII specific content, to focus question more clearly (sorry @πάντα-ῥεῖ for a content changing edit, but I feel it is necessary).编辑 2:删除了 ASCII 特定内容,以更清楚地关注问题(抱歉@πάντα-ῥεῖ 进行内容更改编辑,但我觉得这是必要的)。 Essentially the standard seems to imply some ordering of characters for the basic set, but some encodings do not maintain that ordering, so what's the overriding principle?从本质上讲,该标准似乎暗示了基本集的某些字符排序,但某些编码不保持该排序,那么最重要的原则是什么?

In other words, when are chars in C/C++ not stored in ASCII?换句话说,C/C++ 中的字符何时不存储在 ASCII 中?

C or C++ language don't have any notion of the actual character coding table used by the target system. C 或 C++ 语言没有任何目标系统使用的实际字符编码表的概念。 The only convention is that character literals like 'A' match the current encoding.唯一的约定是像'A'这样的字符文字匹配当前编码。

You could as well deal with EBCDIC encoded characters and the code looks the same as for ASCII characters.您也可以处理EBCDIC编码的字符,并且代码看起来与 ASCII 字符相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM