I want to store CTRL-A (0x01) in a C++ string. Tried the following, but it does not work. Could you tell what I am missing here?
string s = "\u0001";
I get the error when compiled in g++:
error: \u0001 is not a valid universal character
The error you get is due to 2.2/2 in C++03:
If the hexadecimal value for a universal character name is less than 0x20 or in the range 0x7F-0x9F (inclusive), or if the universal character name designates a character in the basic source character set, then the program is ill-formed.
So, for a string literal you have to use \x1
or \1
instead (and you can add leading zeroes to taste). Alternatively if you do only want one character in your string:
string s;
s.push_back(1);
or:
string s(1,1);
The restriction is relaxed in C++11 (2.3/2):
if the hexadecimal value for a universal-character-name outside the c-char-sequence, s-char-sequence, or r-char-sequence of a character or string literal corresponds to a control character (in either of the ranges 0x00–0x1F or 0x7F–0x9F, both inclusive) or to a character in the basic source character set, the program is ill-formed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With