How do i clear a string in C/C++ after using a sprintf() into it?
anonymous
2011-01-10 11:54:17 UTC
what's the easiest way to make that string null again?
Five answers:
SAM
2011-01-10 12:12:48 UTC
In C++, if you are using a std::string object, you may simply initialize that to a empty string.
std::string str = "something";
// your sprintf line
str = "";
Hope this helps!!!
Regards
SAM
anonymous
2016-10-19 13:08:23 UTC
Clear String C
Techwing
2011-01-10 12:07:30 UTC
Set the first character to \0, which terminates the string:
mystring[0]='\0';
Keep in mind that the data is still in the rest of the string, and the memory is still allocated, but subsequent functions that depend on null-terminated strings will see only an empty string.
You can also copy a null string literal into the string:
strcpy(mystring,"");
which has the same effect.
peteams
2011-01-10 15:52:56 UTC
I don't fully understand what you're trying to achieve. Specifically the phrase "make the string null again" feels wrong.
In this code:
char buffer[256];
sprintf(buffer, "My formatted string %d", someNumber);
PassToFunction(buffer);
After the first line buffer is not null, it is just random uninitialised data. After the second line buffer contains nicely formatted text. The third line passes the nicely formatted text to a function where it is used.
After the three lines have executed, if you don't want the data anymore you simply don't refer to it. Unless the buffer contained something sensitive like a password, you don't need to overwrite it.
If the memory for the buffer is allocated like the example above you don't need to do anything special to deallocate it, the compiler will arrange that for you. If the memory was allocated with new or malloc you do need to free it with delete or free.
Chris C
2011-01-10 12:45:19 UTC
While it may seem like overkill, I usually erase the entire string by using memset()