How can I fit this integer into the string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bajajv
    New Member
    • Jun 2007
    • 152

    How can I fit this integer into the string?

    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 -
    Code:
    	char* temp = "id is %d";
    	int id = 1000;
    	char* temp1 = new char[20];
    	memset(temp1, '\0', 20);
    	sprintf(temp1, "%s %d", temp, id);
    	cout << temp1 << endl;
    the output is - Id is %d 1000.
    How can I fit this integer into the string?
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Change temp to "Id is ". You only need one %d.
    By the way, the memset on line 4 is unnecessary.

    Comment

    • bajajv
      New Member
      • Jun 2007
      • 152

      #3
      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.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        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.

        Comment

        • bajajv
          New Member
          • Jun 2007
          • 152

          #5
          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.

          Comment

          Working...