Skip to main content
gamedev.net
🔒 Locked

sprintf question.

Started by OrcishCoder Aug 4, 2005 at 11:11 AM 5 replies 750+ views
Original Post
OrcishCoder
OrcishCoder
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
Deception666
Deception666
If copying occurs between strings that overlap, the behavior is undefined.
dyerseve
dyerseve
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.)
guyaton
guyaton
you could try:

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

~guyaton
SW INC
SW INC
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)
OrcishCoder
OrcishCoder
Thanks you guys. So I wont use that kind of method to copy string in future.


regards,
Martin
Aiursrage2k
Aiursrage2k
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);
}
Insufficent Information: we need more infromationhttp://staff.samods.org/aiursrage2k/

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.