简体   繁体   English

将固定长度的字符数组分配给字符串

[英]Assign a fixed length character array to a string

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. 我想过使用你可以提供n的assign,但忽略了\\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的“对迭代器”形式。

str.assign(test1, std::find(test1, test1 + 4, '\0'));

Character buffers in C++ are either-or: either they are null terminated or they are not (and fixed-length). C ++中的字符缓冲区是 - 或者:它们是空终止的,或者它们不是(和固定长度)。 Mixing them in the way you do is thus not recommended. 因此不建议以您的方式混合它们。 If you absolutely need this, there seems to be no alternative to manual copying until either the maximum length or a null terminator is reached. 如果你绝对需要这个,那么除非达到最大长度或空终止符,否则似乎没有其他方法可以手动复制。

for (char const* i = test1; i != test1 + length and *i != '\0'; ++i)
    str += *i;

You want both NULL termination and fixed length? 你想要NULL终止固定长度? This is highly unusual and not recommended. 这是非常不寻常的,不推荐。 You'll have to write your own function and push_back each individual character. 你必须编写自己的函数并push_back每个角色。

对于第一种情况,当你执行str.assign(test1)和str.assign(test2)时,你的数组必须有/ 0,否则这不是“char *”字符串,你不能将它分配给像这样的std :: string。

看到你的序列化注释 - 使用std::vector<char>std::array<char,4> ,或只是一个4字符数组或容器。

Your second 'bad' example - the one which prints out "Tet" - actually does work, but you have to be careful about how you check it: 你的第二个“坏”例子 - 打印出“Tet”的例子 - 实际上确实有效,但你必须要小心你如何检查它:

str.assign(test2, 4); // BAD "Tet"
cout << "\"" << str << "\"" << endl;

does copy exactly four characters. 确实复制了四个字符。 If you run it through octal dump( od ) on Linux say, using my.exe | od -c 如果你通过Linux上的八进制转储( od )运行它,请使用my.exe | od -c my.exe | od -c you'd get: my.exe | od -c你会得到:

0000000   "   T   e  \0   t   "  \n
0000007

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

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