How to work with unlimited arrays of characters when building C ++ strings?

As stated in What is the C ++ idiom for replacing snprintf (3)? , I parse the file header and create an error message, the byte field in the header is damaged. This code summarizes what I'm trying to do:

const std::string parseCapturePattern(const int fd) { // fd is the descriptor of the ogg file const char CAPTURE_PATTERN[4] = {'O', 'g', 'g', 'S'}; char capture_pattern[4]; read(fd, capture_pattern, sizeof(capture_pattern)); // error handling omitted if (strncmp(capture_pattern, CAPTURE_PATTERN, sizeof(capture_pattern)) != 0) { std::ostringstream err; /*** This won't actually work ***/ err_msg << "Invalid capture pattern: '" << capture_pattern << "'; expecting '" << CAPTURE_PATTERN << "'"; /*** This won't actually work ***/ return err.str(); } } 

This will not work because capture_pattern and capture_pattern are not character arrays with a NULL character. What kind of work is this:

  err_msg << "Invalid capture pattern: '" << capture_pattern[0] << capture_pattern[1] << capture_pattern[2] << capture_pattern[3] << "'; expecting '" << CAPTURE_PATTERN[0] << CAPTURE_PATTERN[1] << CAPTURE_PATTERN[2] << CAPTURE_PATTERN[3] << "'"; 

This, of course, is almost indescribably disgusting.

Any ideas?

+1
source share
2 answers

std::string(capture_pattern, capture_pattern+4) build a string of the first 4 characters of capture_pattern .

+4
source

A few ideas:

Use a string with a null terminating character and use the string search function: const char CAPTURE_PATTERN [] = "OggS";

Then you can use strstr for a null-terminated string. This, of course, is a problem if you do not want to add a null character at the end, but could be useful if you would like to search for a large piece of data immediately with strstr ()

Another idea is to use memcmp (). Like string matching, but works directly on what you pass. You do not need null termination and can still initialize your string with const char CAPTURE_PATTERN [] = "OggS";

0
source

All Articles