Sign in to follow this  
Deek880

converting from char[32] to const char *

Recommended Posts

Deek880    126

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.

 
 

Share this post


Link to post
Share on other sites
RazzleGames    146

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");
	
Edited by RazzleGames

Share this post


Link to post
Share on other sites
SiCrane    11839

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this