繁体   English   中英

在 C++ 如何将字符串数组的元素分配给 char 数组?

[英]in C++ How to assign an element of an array of strings to an array of char?

在 c++ 假设我有:

string s[] = {"red","green","blue"} ;
char c[50] ;

我想做一个这样的任务:

c = s[0] ;

我该怎么做???

无论出于何种目的,请考虑是否可以使用std::string而不是char数组( c )。

如果您仍想这样做,可以使用strcpymemcpy

const char *cstr = s[0].c_str();
size_t len = strlen(cstr);
size_t len_to_copy = len > sizeof c ? sizeof c : len;

memcpy(c, cstr, len_to_copy - 1);
c[len_to_copy - 1] = 0; 

(如果“c”不需要是 C 字符串,则不需要复制一个字节并以 null 字节终止)。

请注意,如果c没有任何空间,这可能会被截断。 也许std::vector<char>更适合(当然取决于用例)。

我会使用std::copy

#include <iostream>
#include <string>

int main()
{
  std::string strings[] = {"string", "string2"};
  char s[10];
  std::copy(strings[0].begin(), strings[0].end(), s);
  std::cout << s; // outputs string
}

使用std::copy的优点是它使用了迭代器。

我会使用std::strncpy 它将归零终止您的缓冲区并且不会越界写入。

char c[50];
std::string test_string = "maybe longer than 50 chars";
std::strncpy(c, test_string.c_str(), sizeof(c));

暂无
暂无

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

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