Reputation: 93
Isn't it possible? When I remove d[%s], it was okay. Would you explain the reason?
std::string toString() const {
char buf[1024];
int a, b, c;
std::string d;
snprintf(buf, 1024, "a[%d] b[%d]" "c[%d] d[%s]", a, b, c, d);
return buf;
}
Upvotes: 1
Views: 1391
Reputation: 37616
snprintf
does not work with std::string
. The %s
modifier is specified as follow:
The argument must be a pointer to the initial element of an array of characters. [...]
You need to pass a null-terminated array of characters. Fortunately, you can use c_str
from std::string
to obtain such pointer.
Just change your code to:
snprintf(buf, 1024, "a[%d] b[%d]" "c[%d] d[%s]", a, b, c, d.c_str());
Upvotes: 2