【问题标题】:Initializing char Buffer with a string in c++在 C++ 中使用字符串初始化 char 缓冲区
【发布时间】:2015-10-15 15:45:16
【问题描述】:

我不想在下面的代码中使用字符串 str 初始化静态字符缓冲区,但我收到以下错误:

错误:初始化时无法将'std::string'转换为>'char'

如果我使用

static char buf[500] = str.c_str();

我收到以下错误:

error: invalid conversion from ‘const char*’ to ‘char*’

下面是我的代码:

std::string str = "<Version="+version+" Ret=\"false\"/>";
static char buf[500] = str;
int len=strlen(buf);
buf[len]='\0';
INFO("Static Buffer :: "<<buf);

【问题讨论】:

  • 嗯,那是因为通过猜测编程是行不通的。
  • 您的buf[len]='\0' 是多余的:根据定义,lenbuf 中已经存在的第一个'\0' 的索引。您所做的只是将'\0' 替换为'\0'

标签: c++ buffer


【解决方案1】:

首先,您不能直接从std::string 初始化char[]。这是不可能的。即使可以,你也会写= str,而不是= { str }

因此,您需要先创建数组,然后手动将std::string 的内容分配给它。遗憾的是,数组是不可赋值的,所以你将不得不使用“算法”来做到这一点。

我们开始吧:

const std::string str = "Hello world";
static char buf[500] = {};
std::copy(
   // from the start of the string
   std::begin(str),

   // to the end of the string, or to 499 chars in, whichever comes first
   std::begin(str) + std::min(str.size(), sizeof(buf)),

   // into buf
   std::begin(buf)
);

呸。

如果可以,而且很可能是这种情况,避免

如果您确实需要包含std::string 内容的C 字符串,只需在需要时访问str.c_str()。一般来说,没有必要保留一个原始的 char 数组,尤其是当您已经拥有合适的工具来完成这项工作时。

此外,由于您没有使用该数据初始化buf,如果它是函数-static,则此代码可能没有预期的效果。

【讨论】:

  • 它给了我错误:“begin”不是“std”的成员..也许 end 和 begin 只能用于数组而不是字符串
  • @yinyang 您正在使用旧版本的标准来编译代码。 Pre-C++11 没有非成员 beginend。将-std=c++14(或至少std=c++11)添加到编译器选项中。
  • 或者直接替换为str.begin()。一点点研究会有很大的帮助:您可以在几分钟内从 cppreference.com 弄清楚这一点。
【解决方案2】:

您可以使用std::string::copy()

std::string text = "Hello there!";
char* cStrText = new char[text.length()];

//Copy the string into the buffer
text.copy(cStrText, text.length(), 0);

显然,这执行的副本可能不是最佳的。您可能需要考虑尝试移动它。

https://www.cplusplus.com/reference/string/string/copy/

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2014-07-26
    • 2013-02-19
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多