cr8ivecodesmith
cr8ivecodesmith

Reputation: 2061

How to pass variable in C++ Sprintf 2nd(format) argument?

I've been cracking heads on how to achieve this in C++:

string format = "what is your %s";  
new_string = sprintf(buffer, format, name);

Any help would be very much appreciated.

Thanks!

Upvotes: 3

Views: 3647

Answers (6)

hmjd
hmjd

Reputation: 122001

The format passed to sprintf must be a char*, not a std::string. sprintf also returns the number of characters written, not a pointer to the constructed buffer.

int len = sprintf(buffer, "what is your%s", name);
std::string new_string(buffer, len);

Another possibility would be to use std::ostringstream to perform your formatting.

Upvotes: 1

Harley Sugarman
Harley Sugarman

Reputation: 293

I'm not sure I understand the problem here - sprintf is a function that takes in a char* as its first argument, and a const char* as its second. These are both C data types, and so I don't know if using a C++ string will be recognised by the compiler as valid.

Also, the function returns an int (the number of characters written), not a string, which it looks like you're expecting with a return value like new_string.

For more information, you can look at http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Upvotes: 0

Vlad
Vlad

Reputation: 18633

You could always do something like:

char buffer[100]; 
string format = "what is your %s";
sprintf(buffer, format.c_str(), name.c_str());
string new_string(buffer);

Alternatively, use a stringstream:

stringstream buf;
buf << "what is your " << name;
string new_string = buf.str();

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409356

Use ostringstream:

std::ostringstream os;
os << "what is your " << name;
std::string new_string = os.str();

Upvotes: 3

Jaffa
Jaffa

Reputation: 12719

You may use stringstream form the C++ STL which is more OO.

Check out the documentation.

sprintf is part of the C library, and thus don't know anything about std::string. Use char* instead if you still want to use it.

To get the C char* string from an std::string, uses c_str method.

Upvotes: -1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

Use format.c_str():

string format = "what is your %s";  
int total = sprintf(buffer, format.c_str(), name);

Also note the returned value is not the new string, it is the buffer which is the output string. The returned value is actually the total number of characters written. This count does not include the additional null-character automatically appended at the end of the string. On failure, a negative number is returned (see doc here).

But in C++, std::ostringstream is better and typesafe, as @Joachim explained in his answer.

Upvotes: 5

Related Questions