Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store CTRL-A (0x01) in a C++ string?

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
like image 546
Sanish Gopalakrishnan Avatar asked Dec 09 '22 05:12

Sanish Gopalakrishnan


1 Answers

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.

like image 156
Steve Jessop Avatar answered Dec 25 '22 20:12

Steve Jessop