繁体   English   中英

如何在 C++ 中连接多个 C 风格的字符串?

[英]How to concatenate multiple C-style strings in C++?

我必须生成一个字符串命令来使用微控制器配置设备,因此需要 C 风格的字符串而不是常规的std::string

每个步骤都需要按回车键或 Y/N + 回车答案,我需要为每个步骤输入一行代码。 代码示例:

#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);
}

我可以以某种方式减少重复 LOC 的数量吗?

使用std::string并完成后,将其复制到command

示范:

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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