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;
}
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 +=
.
Looks to be that your problem is on this line:
bottom += "| " + tmp[j] " ";
You're missing a +
between tmp[j]
and " "
. Try changing it to:
bottom += "| " + tmp[j] + " ";
Edit:
The above will still cause a compilation error, and the one you stated w/ g++, the following will work and result in minimal temporary objects:
bottom += std::string("| ") + tmp[j] + " ";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With