"Felix85" <a.******@gmail.com> wrote in message
news:11*********************@j73g2000cwa.googlegro ups.com...
54 ofstream outfile("../gamefiles/rooms/" +
r.getRoomNumber() + ".room");
i get the error:
room.cpp:54: error: invalid operands of types `const char*' and `const
char[6]' to binary `operator+'
im using gcc version 3.4.5 (Gentoo 3.4.5-r1, ssp-3.4.5-1.0, pie-8.7.9)
so far I can't see anything wrong with it, so any help will be
appreciated.
You are trying to add a character array ".../gamefiles/rooms/" to whatever
r.getRoomNumber() returns (proably an integer) to another character array
".room"
You can't add them together this way, because character arrays are stored as
pointers.
If you didn't have r.getRoomNumber() in there it would be a simple matter to
use std::string to do it.
ofstream outfile( std::string("../gamefiles/rooms/") + ".room" );
or such, because you can add two std::strings to gether, and you can add a
char array to a std::string. You still can't add an integer to it.
Still using std::string you can use some conversion to convert the integer
to a std::string. I use a template I call StrmConvert() which looks like
this:
#include <sstream>
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
and is used like this:
StrmConvert<std::string>( SomeNumber );
So then you could do:
ofstream outfile( ("../gamefiles/rooms/" + StrmConvert<std::string>(
getRoomNumber() ) + ".room").c_str());
This uses a few "tricks", one being if of the arguments to add is a
std::string, then they'll add together to form a std::string. So it adds
the char array to the std::string produced by the StrmConvert and gets a
std::string temporary. Then it adds the other char array to the std::string
temporary. This whole thing is in parenthesis so I can get a const char*
using .c_str() which outfile needs.
Quite a mess isn't it?
There are other ways to do it. You can go the old C style way and use
sprintf into a char buffer, but the you have to worry that the char buffer
is big enough to hold the entire string.
There are also different ways to convert from a number to a char array or a
std::string, that is just my favorite way.
I'm sure you'll get other responses to your post with other ways to do it.
Make sure you understand what everyone is saying and pick the way that suits
you best, but learn from all of them.