tags:

views:

275

answers:

6

Normally you can print the string in C like this..

printf("No record with name %s found\n", inputString);

But i wanted to make a string out of it, how i can do it? I am looking for something like this..

char *str = ("No record with name %s found\n", inputString);

I hope this has clear what i am looking for...

+29  A: 

One option would be to use sprintf, which works just like printf but takes as its first parameter a pointer to the buffer into which it should place the resulting string.

It is preferable to use snprintf, which takes an additional parameter containing the length of the buffer to prevent buffer overruns. For example:

char buffer[1024];
snprintf(buffer, 1024, "No record with name %s found\n", inputString);
James McNellis
+2  A: 

Look into sprintf (see below).

int n = sprintf(str, "No record with name %s found\n", inputString);
Taylor Leese
+2  A: 

Use

sprintf(str, "No record with name %s found\n", inputString);
Cory Petosky
+9  A: 
Benjamin Pollack
As it's a homework question, I'd just to point out that `sizeof output` only gives the number of *elements* in a `char` array - the usual practice is to use: `sizeof array / sizeof array[0]`, which works without being dependent upon the size of various types. Plus, it works for `char` arrays too. :)
Lucas Jones
Good point. Even that, though, can fail in some really common cases, such as passing `array` to a function--at which point, `sizeof array` is 4 or 8 on any modern system, regardless of the number and size of the elements therein. The real solution is to use `std::vector` or something similar and avoid the whole mess entirely.
Benjamin Pollack
+6  A: 

Since this is homework (thanks for tagging it as such) I'll suggest you to look closely at the ...printf() family of functions.

I'm sure you'll find the solution :)

Remo.D
Well, it looks like others alredy deprived you of the pleasure of discovery :)
Remo.D
+1 anyway for giving the right kind of answer to a homework question.
Daniel Pryden
A: 

My man page for printf ("man 3 printf" on any linux box) contains your answer on the 11th line.

Andy Ross