C++ Concating strings result in "invalid operands of types ‘const char*’ and ‘const char"
c++, char, concatenation
Solution
Here:
bottom += "| " + tmp[j] " ";
You are trying to sum a `char` and a pointer to `char`. That won't work (it won't result in the concatenation of the character and the pointed string literal). And the same is true if you add a `+` sign after `tmp[j]`, because that will still be evaluated as (extra parentheses added to stress the fact that `operator +` associates to the left):
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.
If you want to have everything in one line, just do:
bottom += std::string("| ") + tmp[j] + " ";
Now, the above expression on the right side of the assignment will be evaluated as:
(std::string("| ") + tmp[j]) + " ";
Since `operator +` for a `std::string` and a `char` is defined and returns an `std::string`, the result of evaluating the sub-expression within parentheses will be an `std::string`, which is then summed to the string literal `" "`, returning (again) an `std::string`.
Eventually, the result of the whole expression `(std::string("| ") + tmp[j]) + " "` is given in input to `operator +=`.
Problem
I want to concat two strings but i get error that i don't understand how to overcome this error. Is there some way to convert this const char* to char? Should i use some dereferencing? ``` ../src/main.cpp:38: error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’ make: *** [src/main.o] Error 1 ``` However, if i try to make up "bottom" string this way, it works: ``` bottom += "| "; bottom += tmp[j]; bottom += " "; ``` Here is the code. ``` #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; } ```