C++ 连接字符串导致 "invalid operands of types ‘const char*’ 和 ‘const char"

标签 c++ char concat

我想连接两个字符串,但出现错误,我不知道如何克服这个错误。

有什么方法可以将这个 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

但是,如果我尝试以这种方式组成“bottom”字符串,它会起作用:

bottom += "| ";
bottom += tmp[j];
bottom += " ";

这是代码。

#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;
}

最佳答案

这里:

bottom += "| " + tmp[j] " ";

您正在尝试对 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.

如果你想把所有的东西都放在一行中,只需这样做:

bottom += std::string("| ") + tmp[j] + " ";

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

(std::string("| ") + tmp[j]) + " ";

因为 std::stringcharoperator + 被定义并返回一个 std::string,计算括号内子表达式的结果将是一个 std::string,然后将其求和到字符串文字 "",(再次)返回一个 std::string

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

关于C++ 连接字符串导致 "invalid operands of types ‘const char*’ 和 ‘const char",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798623/

相关文章:

c++ - 仅匹配集合中的某些字段

c++ - 将代码从 Visual Basic 移至 C++ 问题

Angular 7路由连接导致编译错误

powershell - 将列表中的行添加到第二个列表Powershell中的行

c# - 使用没有外部变量的 LINQ 连接字典(值)中的所有字符串

c++ - 为什么 C++ 允许在运行时将数组大小传递给函数以构造固定大小的数组?

使用函数指针时c++模板编译错误

python - 打印具有最大字符数的单词(来自用户输入)python

java - 如何在 java 中编写代码来查看 char 是否为 int?

c++ - char指针或char变量的默认值是什么