• Advertisement
Sign in to follow this  

converting from char[32] to const char *

This topic is 1647 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement

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

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

const char * str = &buffer[0];

Share this post


Link to post
Share on other sites

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
Sign in to follow this  

  • Advertisement