[英]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
)。
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.