string with embedded null characters

493 views Asked by At

Is there any way that I can use istringstream to read strings with embedded null characters? For example, if I have a char array "125 320 512 750 333\0 xyz". Is there any way that I could get "xyz" after the null character?

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    std::string stringvalues = "125 320 512 750 333\0 xyz";

    cout << "val: " << stringvalues << endl;

    std::istringstream iss (stringvalues);

    for (int n=0; n<10; n++)
    {
        string val;
        iss >> val;
        std::cout << val << '\n';
    }
    
    return 0;
}

This is an example modified from cplusplus.com. I want to get the part after the null character, and I am curious whether I can get it without knowing the exact length of the char array. Thanks in advance.

2

There are 2 answers

2
KamilCuk On BEST ANSWER

Just properly initialize string with the proper size of the char array. The rest will follow naturally.

#include <sstream>
#include <string>
#include <cstring>
#include <iostream>
#include <iomanip>
int main() {
    const char array[] = "125 320 512 750 333\0 xyz";

    // to get the string after the null, just add strlen
    const char *after_the_null_character = array + strlen(array) + 1;
    std::cout << "after_the_null_character:" << after_the_null_character << std::endl;

    // initialized with array and proper, actual size of the array
    std::string str{array, sizeof(array) - 1};
    std::istringstream ss{str};
    std::string word;
    while (ss >> word) {
        std::cout << "size:" << word.size() << ": " << word.c_str() << " hex:";
        for (auto&& i : word) {
            std::cout << std::hex << std::setw(2) << std::setfill('0') << (unsigned)i;
        }
        std::cout << "\n";
    }
}

would output:

after_the_null_character: xyz
size:3: 125 hex:313235
size:3: 320 hex:333230
size:3: 512 hex:353132
size:3: 750 hex:373530
size:4: 333 hex:33333300
size:3: xyz hex:78797a

Note the zero byte after reading 333.

0
eerorika On

Is there any way that I can use istringstream to read strings with embedded null characters?

Yes. You can use any of the UnformattedInputFunctions such as the read member function to read input including null chars.

Note however that your stringvalues does not contain anything after the null char and thus neither does the string stream constructed from it. If you want a std::string that contains null chars (other than the terminating one), then you can use for example the constructor that accepts a size as second argument.

I want to get the part after the null character, and I am curious whether I can get it without knowing the exact length of the char array.

Here is a simple way:

const char* string = "125 320 512 750 333\0 xyz";
std::size_t length = std::strlen(string);
const char* xyz = string + length + 1;