Jump to content
  • Advertisement
Sign in to follow this  
OrcishCoder

sprintf question.

This topic is 4856 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

sorry my question might be stupid to you, but i really want to know a confident answer: char buffer[256]; . . . //buffer now contain string "Empty" let say. sprintf(buffer, "[ %s ]", buffer); <-- will this cause problem? I hope in final, buffer = "[ Empty ]". I cant show my code, because it is too long. And my program always got unpredictable bugs that very hard to reproduce. I checked my code, I suspect this sprintf might cause problem, but i dont sure, please help. Thanks in advance. regards, Martin

Share this post


Link to post
Share on other sites
Advertisement
Im no expert on sprintf (I stick to std::string and stringstreams and such), but that's probably not going to work. I tried it in Visual C++ 6.0, and on the implementation they use it does work. You get something like "[ [ [ [ ]". I'm not sure what the official ANSI specifications say about this, but I would just create a temporary buffer. (Actually I'd just use std::string.)

Share this post


Link to post
Share on other sites
you could try:


char tempBuffer[256] = {0};

sprintf( tempBuffer, "[ %s ]", buffer );
memcpy( buffer, tempBuffer, sizeof(char)*256 );


Share this post


Link to post
Share on other sites
why use the extra memcpy?

char tempbuffer[256];
.
.
.
//buffer now contain string "Empty" let say.

char buffer[256];

sprintf(buffer, "[ %s ]", tempbuffer);

works with out the extra waste of time for a memcpy (and is cleaner)

Share this post


Link to post
Share on other sites
I dont think there would be a problem with that. Could use something like

char tmp[256];
int i;
tmp = '[';
for(i=1; i<254 && *(buffer+i); i++)
{
*(tmp+i) = *(buffer+i-1);
}
*(tmp+i) = ']';
*(tmp+i+1) = '\0';
for(i=0; *(tmp+i); i++)
{
*(buffer+i) = *(tmp+i);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!