8

I was looking at a way to achieve sprintf() functionality with std::string and I found a good answer from std::string formatting like sprintf. This is somewhat hacky though because it writes directly to the pointer returned from string.c_str(). So I reimplemented it using a char * with malloc() and realloc().

std::string string_format(const char * format, ...) { size_t size; size_t n; va_list args; char * buffer; std::string str; size = 100; buffer = malloc(size); for (;;) { va_start(args, format); n = vsnprintf(buffer, size, format, args); va_end(args); if (n > -1) { if (n < size) { size = n; break; } size = n + 1; } else { size *= 2; } buffer = realloc(buffer, size); } str = std::string(buffer, size); free(buffer); return str; } 

I know I could just do:

str = std::string(buffer); 

But then it will have to essentially do strlen(buffer). I could make it a little better by:

str = std::string(buffer, size); 

But would using string.swap() be more efficient by swapping the internal buffer instead of copying it?

str.swap(std::string(buffer, size)); 

Is there a better way to do this?

6
  • You can write to the buffer retrieved by &str[0] in C++11 as long as you stop before the null, and don't touch the null at all. Commented Feb 8, 2013 at 4:11
  • to add to @chris, you can also use string::reserve to expand it Commented Feb 8, 2013 at 4:14
  • 2
    It may be worth it to see how boost format does it. Also, have you considered using variadic templates instead of varargs? Commented Feb 8, 2013 at 4:14
  • Arguably, Yes swap will be more efficient unless you prove otherwise by posting profiling data for both the cases. And If you are really serious about this being a bottle neck then you should be doing that. Commented Feb 8, 2013 at 4:15
  • 2
    I think you should profile your program, to see if this is really a bottleneck. Commented Feb 8, 2013 at 4:15

1 Answer 1

18

Just use str.assign(buffer, size);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.