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 \0s. 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?
\0in each array?