考虑以下代码:
#include <iostream>
#include <typeinfo>
int main(){
std::string word = "This is string";
std::string word1 = "a" + word[0];
std::cout << word1;
}
正如你所看到的,我有一个带有名称的字符串word
我想将它的第一个字母添加到另一个字符串并将它们存储到字符串word1
。当我运行代码时,我期望输出是aT
,但输出是 ╨≥ ╨≥ ╨≥ ╨≥ P≥ ►≥ @≥ ╕♠≥
!这是什么意思?我如何解决它? (另请注意,我的 IDE 是 Code::Blocks 20.03)
"a"
不是一个字符串(嗯,它是一个 c 字符串,但不是一个std::string
,而 c 字符串只是一个数组)。它是const char[2]
并衰减为指针时+
被申请;被应用。有一个operator+
for std::string
though:
std::string word1 = std::string("a") + word[0];
or
std::string word1 = "a"s + word[0];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)