【问题标题】:How to concatenate multiple C-style strings in C++?如何在 C++ 中连接多个 C 风格的字符串?
【发布时间】:2020-10-22 08:27:39
【问题描述】:

我必须生成一个字符串命令来使用微控制器配置设备,因此需要 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 的数量吗?

【问题讨论】:

  • 如果command是全局的,你可以写一个包装函数catCommand至少避免参数重复3次。此外,如果用户提供了一个长密码,那么那里就会出现缓冲区溢出。
  • 为什么不生成std::string,然后使用c_str()
  • 你可以写std::strcat(std::strcat(std::strcat(command, YES), getTelnetPassword()), ENTER);。这只是一条线,但我不会称之为改进。尽量减少代码行数有点人为。尽量使代码尽可能清晰,不管需要多少行。
  • API 调用将const car * 作为参数并不意味着您不能使用std::string 来生成和保存字符串数据。这只是意味着您需要找到一种方法(例如c_str)将其传递给 API。
  • 请注意,最小化 LOC 并不意味着减少汇编代码

标签: c++ string


【解决方案1】:

使用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;
}

【讨论】:

  • 包括&lt;string&gt; 和使用std::string 哪怕只是短暂的也不会给微控制器带来负担?该模块只是将要使用的更大软件的一小部分。
  • @AndreiVicol 如果您使用的是 MCU,请在问题中标记它
猜你喜欢
  • 2013-05-24
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2012-01-17
  • 1970-01-01
相关资源
最近更新 更多