簡體   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