将固定长度的字符数组分配给字符串 [英] Assign a fixed length character array to a string
本文介绍了将固定长度的字符数组分配给字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个固定长度的字符数组我想分配给一个字符串。问题出现,如果字符数组已满,分配失败。我想到使用assign可以提供 n
但是忽略 \0
。例如:
I have a fixed length character array I want to assign to a string. The problem comes if the character array is full, the assign fails. I thought of using the assign where you can supply n
however that ignores \0
s. For example:
std::string str;
char test1[4] = {'T', 'e', 's', 't'};
str.assign(test1); // BAD "Test2" (or some random extra characters)
str.assign(test1, 4); // GOOD "Test"
size_t len = strlen(test1); // BAD 5
char test2[4] = {'T', 'e', '\0', 't'};
str.assign(test2); // GOOD "Te"
str.assign(test2, 4); // BAD "Tet"
size_t len = strlen(test2); // GOOD 2
如何为这两种情况正确地为字符串分配固定长度的字符数组?
How can I assign a fixed length character array to a string correctly for both cases?
推荐答案
使用assign的迭代器对形式。
Use the "pair of iterators" form of assign.
str.assign(test1, std::find(test1, test1 + 4, '\0'));
这篇关于将固定长度的字符数组分配给字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文