C++ Concating字符串导致"类型'const char*'和'const char"的无效操作数

boo*_*oka 6 c++ concat char

我想连接两个字符串,但我得到错误,我不明白如何克服此错误.

有没有办法将此const char*转换为char?我应该使用一些解除引用吗?

../src/main.cpp:38: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’
make: *** [src/main.o] Error 1
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试以这种方式组成"底部"字符串,它的工作原理:

bottom += "| ";
bottom += tmp[j];
bottom += " ";
Run Code Online (Sandbox Code Playgroud)

这是代码.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <sstream>

int main(int argc, char* argv[]) {

    ifstream file("file.txt");

    vector<string> mapa;
    string line, top, bottom;

    while(getline(file,line)){
        mapa.push_back(line);
    }

    string tmp;
    for(int i = 0; i < mapa.size(); i++)
    {
        tmp = mapa[i];
        for(int j = 0; j < tmp.size(); j++)
        {
            if(tmp[j] != ' ')
            {
                top += "+---";
                bottom += "| " + tmp[j] + " ";
            } else {

            }
        }
        cout << top << endl;
        cout << bottom << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 7

这里:

bottom += "| " + tmp[j] " ";
Run Code Online (Sandbox Code Playgroud)

您正在尝试将a char和指针相加char.这将不起作用(它不会导致字符和指向的字符串文字的串联).如果你之后添加一个+符号也是如此tmp[j],因为它仍然会被评估为(添加额外的括号以强调operator +左边的关联事实):

bottom += ("| " + tmp[j]) + " "; // ERROR!
//         ^^^^^^^^^^^^^
//         This is still summing a character and a pointer,
//         and the result will be added to another pointer,
//         which is illegal.
Run Code Online (Sandbox Code Playgroud)

如果你想把所有东西放在一行,那就做:

bottom += std::string("| ") + tmp[j] + " ";
Run Code Online (Sandbox Code Playgroud)

现在,赋值右侧的上述表达式将被评估为:

(std::string("| ") + tmp[j]) + " ";
Run Code Online (Sandbox Code Playgroud)

因为operator +a std::string和a char被定义并返回a std::string,所以在括号中计算子表达式的结果将是a std::string,然后将其求和到字符串文字中" ",然后返回(再次)a std::string.

最终,整个表达式的结果(std::string("| ") + tmp[j]) + " "在输入中给出operator +=.


Nat*_*nst 3

看来您的问题出在这一行:

bottom += "| " + tmp[j] " ";
Run Code Online (Sandbox Code Playgroud)

你缺少和+之间的一个。尝试将其更改为:tmp[j]" "

bottom += "| " + tmp[j] + " ";
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的内容仍然会导致编译错误,而您使用 g++ 所说的错误,以下内容将起作用并产生最少的临时对象:

bottom += std::string("| ") + tmp[j] + " ";
Run Code Online (Sandbox Code Playgroud)