How to save CTRL-A (0x01) in a C ++ line?

I want to save CTRL-A (0x01) in a C ++ line. Tried the following, but it does not work. Could you tell me what I miss here?

string s = "\u0001"; 

I get an error when compiling in g ++:

 error: \u0001 is not a valid universal character 
+4
source share
4 answers

The error you get is related to 2.2 / 2 in C ++ 03:

If the hexadecimal value for the universal symbolic name is less than 0x20 or in the range 0x7F-0x9F (inclusive), or if the universal symbolic name indicates the symbol in the main symbol of the set source, then the program is poorly formed.

So, for a string literal, you need to use \x1 or \1 instead (and you can add zero zeros to it). Alternatively, if you only need 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 the universal name character outside c is a char sequence, s is a char sequence or r is a char sequence or a String literal matches a control character (in either of the ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or character in the main character set of the source, the program is poorly formed.

+5
source

Since you already have the value in hex, this is very simple:

 std::string s = "\x01"; 

This works for any hex char literal. The general format is \x<hex number> .

+4
source

you can use

 std::string s = "\001"; 

Please note that the code is octal.

+2
source

A string stores ASCII characters; the compiler must translate from the input character set to ASCII. This mapping is an implementation; it looks like your compiler provider decided not to display from U + 0001 to ASCII 0x01.

You should be able to initialize the string using

 string s = "\001"; 
+2
source

Source: https://habr.com/ru/post/1379292/


All Articles