我想连接两个字符串,但出现错误,我不知道如何克服这个错误。
有什么方法可以将这个 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::string
和 char
的 operator +
被定义并返回一个 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/