如何在 C++ 中存储 CTRL-A (0x01)细绳?
我想将 CTRL-A (0x01) 存储在 C++ 字符串中。尝试了以下方法,但不起作用。你能告诉我这里缺少什么吗?
string s = "\u0001";
在 g++ 中编译时出现错误:
error: \u0001 is not a valid universal character
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您收到的错误是由于 C++03 中的 2.2/2 引起的:
因此,对于字符串文字,您必须使用
\x1
或\1
(并且您可以根据需要添加前导零)。或者,如果您只想在字符串中包含一个字符:或:
C++11 (2.3/2) 中放宽了限制:
The error you get is due to 2.2/2 in C++03:
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:or:
The restriction is relaxed in C++11 (2.3/2):
由于您已经有了十六进制值,因此非常简单:
这适用于任何十六进制字符文字。一般格式为
\x<十六进制数字>
。Since you already have your value in hexadecimal it's very simple:
This works for any hexadecimal char literal. The general format is
\x<hex number>
.您可以使用
注意代码是八进制的。
You can use
Note that the code is octal.
string
存储 ASCII 字符;编译器需要将输入字符集转换为 ASCII。此映射是实现定义的;看来您的编译器供应商已决定不从 U+0001 映射到 ASCII 0x01。您应该能够使用以下命令初始化字符串
A
string
stores ASCII characters; the compiler needs to translate from the input character set to ASCII. This mapping is implementation defined; it appears your compiler vendor has decided not to map from U+0001 to ASCII 0x01.You should be able to initialize the string using