2

So it is tempting to do this:

char buf[1024] = "this is"; std::sprintf(buf, "%s test", buf); 

But it is undefined behaviour. I suppose it can be solved via temporary:

char buf[1024] = "this is"; std::sprintf(buf, "%s test", std::string(buf).c_str()); 

What are the downsides of this approach?

5
  • 1
    Alternatives: strcpy (in this case); sprintf(buf + strlen(buf), " test");. You should also consider using the safer versions (sprintf_s). Commented Dec 22, 2019 at 21:42
  • 1
    This is C++, you should be using a std::string instead of a char[] to begin with: string buf = "this is"; buf += " test"; Commented Dec 22, 2019 at 21:48
  • @RemyLebeau true, but for various reasons it has to be as presented in the example Commented Dec 22, 2019 at 21:50
  • 1
    @1201ProgramAlarm sprintf_s is not any safer than sprintf, as well as not being widely supported. snprintf would be a better option Commented Dec 22, 2019 at 22:29
  • @M.M I meant snprintf but the wrong function name came to mind. Sigh. Commented Dec 23, 2019 at 2:59

1 Answer 1

6

To append a string to a char array use strcat:

char buf[1024] = "this is"; std::strcat(buf, " test"); 
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you cast " test" to char *?
or memmove (buf + strlen(buf), " test", sizeof " test");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.