user1984300 user1984300 - 2 months ago 15
C++ Question

Invalid operands of types ‘const char [8]’ and ‘const char*’ to binary ‘operator+

I am trying to write a Fopen statement like this:

FILE *fp;
fp = fopen("client." + receiver->get_identifier().c_str() + ".vol", "a+");


where receiver->get_identifier() returns a string. However, I am getting the error in the title. I read the question here but wasn't having any luck because the first argument of fopen is const char*. What do I have to change to get this to compile?

Answer
receiver->get_identifier().c_str()

returns a const char*, not a std::string, so operator+ cannot kick in (one argument of it must be a std::string). Removing the c_str() and converting at the end with std::string::c_str() should do the trick

fopen(("client." + receiver->get_identifier() + ".vol").c_str(), "a+");

This is because you'd have a const char* plus a std::string, and operator+ will work.

If you may wonder why one cannot define an operator+ for const char*s, that's because C++ does not allow operator overloading for fundamental types; at least one argument must be of a user-defined type.