Reputation: 1022
Is there a way to have and process null value inside std::basic_string
?
Sometimes the string sequence being passed has null values. For example below code outputs 1234,5678 instead of whole string.
#include <iostream>
#include <string>
#include <cstring>
int main ()
{
int length;
std::string str = "1234,5678\000,ABCD,EFG#";
std::cout << "length"<<str.c_str();
}
I need to get the complete string.
Upvotes: 2
Views: 243
Reputation: 254701
First, you'll have to tell the string constructor the size; it can only determine the size if the input is null-terminated. Something like this would work:
std::string str("1234,5678\000,ABCD,EFG#", sizeof("1234,5678\000,ABCD,EFG#")-1);
There's no particularly nice way to avoid the duplication; you could declare a local array
char c_str[] = "1234,5678\000,ABCD,EFG#"; // In C++11, perhaps 'auto const & c_str = "...";'
std::string str(c_str, sizeof(c_str)-1);
which might have a run-time cost; or you could use a macro; or you could build the string in pieces
std::string str = "1234,5678";
str += '\0';
str += ",ABCD,EFG#";
Finally, stream the string itself (for which the size is known) rather than extracting a c-string pointer (for which the size will be determined by looking for a null terminator):
std::cout << "length" << str;
UPDATE: as pointed out in the comments, C++14 adds a suffix for basic_string
literals:
std::string str = "1234,5678\000,ABCD,EFG#"s;
^
which, by my reading of the draft standard, should work even if there is an embedded null character.
Upvotes: 6
Reputation: 38949
You can do this with std::string(std::initalizer_list<char> il)
it's just a little bit of a pain in the neck:
string str{'1', '2', '3', '4', ',', '5', '6', '7', '8', '\0', '0', '0', ',', 'A', 'B', 'C', 'D', ',', 'E', 'F', 'G', '#'};
cout << "length: " << str.size() << ": " << str;
Outputs:
length: 22: 1234,567800,ABCD,EFG#
Upvotes: 1