简体   繁体   中英

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. 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). 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? This is highly unusual and not recommended. You'll have to write your own function and push_back each individual character.

对于第一种情况,当你执行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:

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 my.exe | od -c you'd get:

0000000   "   T   e  \0   t   "  \n
0000007

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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