C++中为何无法拼接字符串与另一字符串的字符?异常输出解析
问题原因与修复方案
异常原因
"a" + word[0]的写法完全不符合你预期的字符串拼接逻辑:
"a"是C风格字符串常量,在表达式中会被隐式转换为const char*类型的指针;word[0]是char类型,会自动提升为int(值为字符'T'的ASCII码84);- 两者相加时,实际是指针地址偏移运算:把
"a"的起始地址加上84,得到一个指向内存随机区域的非法指针; - 用这个非法指针初始化
std::string时,会从该位置开始读取字节直到遇到'\0',自然会输出乱码。
修复方法
提供三种可行的修复方式:
方式一:将C风格字符串转为std::string后拼接
#include <iostream> #include <string> // 原代码漏了<string>头文件,标准C++中必须显式引入 int main(){ std::string word = "This is string"; std::string word1 = std::string("a") + word[0]; std::cout << word1; }
方式二:分步拼接字符
#include <iostream> #include <string> int main(){ std::string word = "This is string"; std::string word1; word1 += 'a'; word1 += word[0]; std::cout << word1; }
方式三:先构造单字符字符串再拼接
#include <iostream> #include <string> int main(){ std::string word = "This is string"; std::string word1(1, 'a'); word1 += word[0]; std::cout << word1; }
内容的提问来源于stack exchange,提问作者user17198641
相关产品推荐
相关产品推荐

