Pedro Martins
Pedro Martins

Reputation: 47

How to use more arguments when calling functions?

Sorry, I know this is really basic, but I don't know how to search it the proper way, so here we go. I'm trying to call MessageBoxA, and I want the message to replace '%s' with something else. Example:

MessageBoxA(0, TEXT("You have %s items"), "title", 0);

Can anyone help me? And once again, I know this is really basic, sorry.

Upvotes: 1

Views: 109

Answers (4)

user4815162342
user4815162342

Reputation: 154916

You can write a utility function to build a std::string from a printf-style format:

#include <cstdio>
#include <cstdarg>
#include <string>
#include <vector>

std::string build_string(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    size_t len = vsnprintf(NULL, 0, fmt, args);
    va_end(args);
    std::vector<char> vec(len + 1);
    va_start(args, fmt);
    vsnprintf(vec.data(), len + 1, fmt, args);
    va_end(args);
    return std::string(vec.begin(), vec.end() - 1);
}

With this function in place, you can create arbitrary strings and pass pointers to their contents as downward-arguments:

MessageBoxA(0, build_string("You have %d items", item_count).c_str(), "title", 0);

It has the advantage of simplicity (several lines of code using only stdio without dependency on iostreams), and has no arbitrary limits on the size of string.

Upvotes: 0

MSalters
MSalters

Reputation: 179819

Use boost::format.

In your example: MessageBoxA(0, (boost::format("You have %1 items") % "title").c_str(), 0);

One advantage is that you don't need to remember all those %s codes anymore, another is that you're no longer limited by the set of built-in flags.

The ( ).c_str() is needed because MessageBoxA is a C interface, not C++, and c_str() converts a C++ string to a C string.

Upvotes: 0

Martin Schlott
Martin Schlott

Reputation: 4547

For MessageBoxA it is:

char szBuf[120];
snprintf(szBuf,120, "You have %s items",nItemCount);
MessageBoxA(0, szBuf, "title", 0);

It is ugly, but it will fit your need.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400274

You have to build the string yourself. In C++, this is typically done with std::ostringstream, e.g.:

#include <sstream>
...

std::ostringstream message;
message << "You have " << numItems << " items";
MessageBoxA(NULL, message.str().c_str(), "title", MB_OK);

In C, this is typically done with snprintf(3):

#include <stdio.h>
...

char buffer[256];  // Make sure this is big enough
snprintf(buffer, sizeof(buffer), "You have %d items", numItems);
MessageBoxA(NULL, buffer, "title", MB_OK);

Upvotes: 8

Related Questions