2

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.

2
  • @Manwal That would be the c_str() member function of the standard C++ string class. What does it look like? Commented Nov 19, 2014 at 12:41
  • Can you use C++ 14? Also I hate C strings D= Commented Nov 19, 2014 at 12:45

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

There's also the basic_string literal suffix s in C++14, the latest libc++ and libstdc++ both support it.
@user657267: Thanks, I'm not yet familiar with C++14. Do you know whether it works if there's a null character in the literal string?
@user657267: I guess it does, since the operator is passed the length of the literal.
I believe so, can't say I've actually used it yet and for some reason gcc 4.9.1 isn't finding it...should work in theory though.
1

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#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.