By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,118 Members | 1,134 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,118 IT Pros & Developers. It's quick & easy.

How can I fit this integer into the string?

bajajv
100+
P: 152
I have a string as - "Id is %d" and an integer as 1000. I want a final string as - "Id is 1000".

I tried like this -
Expand|Select|Wrap|Line Numbers
  1.     char* temp = "id is %d";
  2.     int id = 1000;
  3.     char* temp1 = new char[20];
  4.     memset(temp1, '\0', 20);
  5.     sprintf(temp1, "%s %d", temp, id);
  6.     cout << temp1 << endl;
  7.  
the output is - Id is %d 1000.
How can I fit this integer into the string?
Nov 23 '10 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 2,398
Change temp to "Id is ". You only need one %d.
By the way, the memset on line 4 is unnecessary.
Nov 23 '10 #2

bajajv
100+
P: 152
Actually, I am getting the string from some other function, and it is possible that I may get more than one "%d", so I need to put it at run time.
Nov 23 '10 #3

Expert 100+
P: 2,398
What should your program do if that other function puts two "%d"'s in temp? Might that other function put "%f" or %s" in temp? Can you trust that other function not to put something crazy in temp?

The answer to these questions will determine how carefully your program needs to examine the contents of temp before calling sprintf.
Nov 23 '10 #4

bajajv
100+
P: 152
There are chances that the other function may return string containing 2, 3 or may be more %ds, but I do get the count for that.
Only thing is, I want to add my integers into that string wherever %d comes.
Nov 23 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.