【问题标题】:Why do i can't add an string to an letter of another string?为什么我不能将一个字符串添加到另一个字符串的字母中?
【发布时间】:2022-08-18 18:07:50
【问题描述】:

考虑以下代码:

#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)

    标签: c++ c++17 stdstring


    【解决方案1】:

    "a" 不是字符串(嗯,它是一个 c 字符串,但不是 std::string,而 c 字符串只是一个数组)。它是一个const char[2],并在应用+ 时衰减为一个指针。不过,std::string 有一个 operator+

    std::string word1 = std::string("a") + word[0];
    

    或者

    std::string word1 = "a"s + word[0];
    

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多