-2
\$\begingroup\$

I'm trying to find a simplest solution to append a newline character to a string.

Although the following code works, I would like to know if it's possible to make the code simpler. (The argument should be const char* and not std::string)

My Code :

static void sysGui(const char *s)
{
    char buf[1000];
    std::strcpy(buf, s);
    std::size_t size = std::strlen(s);
    buf[size] = '\n';
    buf[size + 1] = '\0';
    sys_gui(buf);
}
\$\endgroup\$
5
  • \$\begingroup\$ what does sys_gui do? \$\endgroup\$ Aug 10, 2018 at 11:49
  • \$\begingroup\$ @ratchetfreak it sends the string to Tk widgets. It takes char* as an argument. \$\endgroup\$
    – Zack Lee
    Aug 10, 2018 at 11:55
  • 1
    \$\begingroup\$ What do you do is the string is longer than 999 characters? You should allocate the exact needed size not just 1000. \$\endgroup\$
    – MrSmith42
    Aug 10, 2018 at 12:02
  • \$\begingroup\$ @MrSmith42 The string will always be less than 1000. \$\endgroup\$
    – Zack Lee
    Aug 10, 2018 at 12:06
  • \$\begingroup\$ @TobySpeight I just edited that Sir. \$\endgroup\$
    – Zack Lee
    Aug 10, 2018 at 12:11

1 Answer 1

3
\$\begingroup\$

If you're really certain of the necessary conditions for this to actually work, a somewhat cleaner way to do the job would be to use sprintf:

static void sysGui(const char *s)
{
    char buf[1000];
    sprintf(buf, "%s\n", s);
    sys_gui(buf);
}

You could use a std::ostringstream instead, but sprintf seems more in keeping with the fact that the rest of the code is essentially C anyway (regardless of how it's tagged).

\$\endgroup\$
2
  • \$\begingroup\$ This is a cleaner and simpler solution indeed. Thank you so much! \$\endgroup\$
    – Zack Lee
    Aug 10, 2018 at 15:19
  • \$\begingroup\$ I'd probably still recommend a healthy defensiveness, even if "really certain", by using e.g. std::snprintf() at very little extra cost. \$\endgroup\$ Aug 15, 2018 at 13:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.