-1

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?

Community
  • 1
  • 1
user1984300
  • 101
  • 3
  • 15
  • Dupe of [this](http://stackoverflow.com/questions/23936246/error-invalid-operands-of-types-const-char-35-and-const-char-2-to-binar) but is really just a typo. Get rid of the `.c_str` and wrap the whole thing in () and then use `.c_str()`. – NathanOliver Sep 23 '16 at 16:03

2 Answers2

3
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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
2

Try changing the first argument to

(string("client.") + receiver->get_identifier() + ".vol").c_str()

This will add std::string objects with C-Style strings, which can be done, and only take the character pointer at the end (via .c_str()). Your code now tries to add C-Style strings, which is not possible.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185