converting from char[32] to const char *

Started by
3 comments, last by SiCrane 10 years, 9 months ago

Hello:

I am trying to create a text outfile for a class object after compile time to record data.

I need a way to convert from char * to const char *;

the following does not work:


void CPlayer::InitTxtFile(char * gamename)
{

           char buffer[64];
           sprintf(buffer,"%s.txt",gamename);

           ofstream myfile(buffer);

}

Lets say that gamename variable = Vegas. How do I make ofstream myfile(buffer) work the same as ofstream myfile("Vegas.txt");

Any suggestions are most appreciated.


Advertisement

The code, as it is, works just fine. What errors are you getting?

Please change from sprintf to snprintf. If your string, gamename, is any larger than 64 chars, minus one for null and minus sizeof(".txt"), you're hosed.


const int BUFF_SIZE = 64;
char buffer[BUFF_SIZE];
snprintf(buffer, BUFF_SIZE, "%s.txt",gamename)

But a better question is why do you need to create this temp char array to begin with? Why not just use std::string conveniences?


	void CPlayer::InitTxtFile(std::string gamename)
	{
	 
	   std::string path = gamename + ".txt";
	 
	   ofstream myfile(path.c_str());
	 
	}
	// Calling
	// Assuming, somewhere a ptr of CPlayer was created
	cplayer->InitTxtFile("your_game_name");
	

If you only want to convert char buffer[64] to const char *. Then you can do this:


const char * str = &buffer[0];
“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”? Nigel Marsh

While correct, that's fairly pointless. An array implicitly decays to a pointer to the first element.

This topic is closed to new replies.

Advertisement