I’m interested (for various reasons) format using sprintf with the result in a std::string object. The most syntactically direct way I came up with is:
char* buf;
sprintf(buf, ...);
std::string s(buf);
Any other ideas?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Don’t use the
printfline of functions for formatting in C++. Use the language feature of streams (stringstreams in this case) which are type safe and don’t require the user to provide special format characters.If you really really want to do that, you could pre-allocate enough space in your string and then resize it down although I’m not sure if that’s more efficient than using a temporary char buffer array: