Jump to content

  • Log In with Google      Sign In   
  • Create Account

converting from char[32] to const char *


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 Deek880   Members   -  Reputation: 124

Like
0Likes
Like

Posted 16 July 2013 - 12:44 PM

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.

 
 



Sponsor:

#2 Brother Bob   Moderators   -  Reputation: 8201

Like
0Likes
Like

Posted 16 July 2013 - 12:51 PM

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



#3 RazzleGames   Members   -  Reputation: 146

Like
1Likes
Like

Posted 17 July 2013 - 10:49 AM

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, 17 July 2013 - 11:01 AM.


#4 _greyfox()   Members   -  Reputation: 1133

Like
0Likes
Like

Posted 18 July 2013 - 08:46 AM

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

#5 SiCrane   Moderators   -  Reputation: 9598

Like
3Likes
Like

Posted 18 July 2013 - 08:48 AM

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






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS