Is it possible to measure the necessary buffer for sprintf in Microsoft C ++?

I am writing a small conceptual console program with Visual Studio 2008, and I wanted it to output colored text for readability. For coding convenience, I also wanted to make a quick replacement for printf, something where I could write like this:

MyPrintf(L"Some text \1[bright red]goes here\1[default]. %d", 21);

This will be useful because I also create and pass strings in some places, so my strings will contain formatting information.

However, I hit the wall against wsprintf, because I can’t find a function that would let me know the size of the required buffer before passing it to the function. I could, of course, allocate 1 MB to be sure, but that would be ugly, and I would prefer to leave this as a backup solution if I don't find a better way.

In addition, I am also considering the possibility of using std::wstring(I actually look more like a C-guy with little experience in C ++, so now I find a simple-old-w980 -arrays), but it doesn’t have something like wsprintf, where you could build a string with the values ​​replaced in them.

So ... what should I do?

+3
source share
6 answers

_ snwprintf. , , . _snwprintf , , , . , , .

+3

++, , std:: wstringstream - . :

#include <sstream>

void func()
{
    // ...

    std::wstringstream ss;  // the string stream

    // like cout, you can add strings and numbers by operator<<
    ss << L"Some text \1[bright red]goes here\1[default]. " << 21;

    // function takes a C-style const wchar_t* string
    some_c_function(ss.str().c_str()); // convert to std::wstring then const wchar_t*
    // note: lifetime of the returned pointer probably temporary
    // you may need a permanent std::wstring to return the c_str() from
    // if you need it for longer.

    // ...
}
+4

++. , sprintf, .

+3

boost, boost::format. std::string s sprintf. C-, . example.

+2

std::wstring , - c_str, .

, .

When you need the actall string, just use the c_str method:

wprintf(L"string %s recieved!", myWString.c_str());
0
source

Source: https://habr.com/ru/post/1732871/


All Articles