简体   繁体   中英

How to concatenate multiple C-style strings in C++?

I have to generate a string command to configure a device using a microcontroller, hence the need for C-style strings instead of regular std::string .

Each step requires an enter press or a Y/N + enter answer and I need a line of code for each one. Code example:

#define YES "Y\n"
#define NO "N\n"
#define ENTER "\n"
#define DEFAULT_COMMAND_SIZE 30
    
static char command[DEFAULT_COMMAND_SIZE];

if (getChangePassword()) { // just a function that returns true if password has to be changed
    if (getTelnetPassword() != nullptr) {
        std::strcat(command, YES);
        std::strcat(command, getTelnetPassword()); // password is a char*, same as command
        std::strcat(command, ENTER);
    }
} else {
    std::strcat(command, NO);
}

Can I somehow reduce the number of repeating LOC?

Use a std::string and once done, copy it into command :

Demonstration:

#include <iostream>
#include <string>
#include <string.h>

#define YES "Y\n"
#define NO "N\n"
#define ENTER "\n"
#define DEFAULT_COMMAND_SIZE 30

static char command[DEFAULT_COMMAND_SIZE];

bool getChangePassword()
{
  return true;
}

char *getTelnetPassword()
{
  return (char*)"testpassword";
}

int main()
{
  std::string scommand;
  if (getChangePassword()) { // just a function that returns true if password has to be changed
    if (getTelnetPassword() != nullptr) {
      scommand += YES;
      scommand += getTelnetPassword();
      scommand += ENTER;
    }
  }
  else {
    scommand = NO;
  }

  std::strcpy(command, scommand.c_str());

  std::cout << command;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM