将整数添加到字符

addition of integer to char

本文关键字:字符 添加 整数      更新时间:2023-10-16

有人可以解释一下这里发生了什么,在第一个将 char 添加到 int 中,ASCII 值工作正常

但在第二个不起作用你能解释一下它是如何工作的吗?

#include<iostream>
using namespace std;
int main(){ 
    string str="1234";
    str[0]=str[0]+1;    //working fine 
    cout<<str<<endl;
    str[1]=str[1]+'c';   //printing some new character at 1 position
    cout<<str<<endl;
}

我是 n

str[1] = str[1] + 'c' '2' + 'c' ,这与 2 + 'c' 不同。

在ascii中,'2'50,而'c'99

它的总和是 149 不在 ascii (0-127) 的范围内,因此显示的字符取决于您使用的扩展 ASCII(可能ò)。

如果你想有2 + 'c',你必须在你的情况下做str[1] = str[1] + 'c' - '0'