如何在 C++ 中使用 std::cout 正确显示十六进制字符串文字?

How to display character string literals with hex properly with std::cout in C++?

如何在C++中用std::cout正确显示十六进制字符串文字?

我想在 C++ 中使用八进制和十六进制打印带有 std::cout 的字符串文字。

我要打印"bee"。

#include <iostream>
int main() {
    std::cout << "b5e" << std::endl;//1
    std::cout << "b\x65e" << std::endl;//2
    return 0;
}

//1 工作正常,但 //2 没有超出范围的十六进制转义序列。

现在我要打印 "be3"。

#include <iostream>
int main() {
    std::cout << "b53" << std::endl;//1
    std::cout << "b\x653" << std::endl;//2
    return 0;
}

此外,//1 工作正常,但 //2 不使用超出范围的十六进制转义序列。

现在可以得出结论hex不是显示字符串字符的好方法吗?

我觉得我错了,但不知道为什么。

谁能解释一下是否可以使用十六进制以及如何使用?

十六进制转义序列变成\x65e\x653所以你需要帮助编译器在65:

之后停止
#include <iostream>

int main() {
    std::cout << "b\x65""e" << std::endl;//2
    std::cout << "b\x65""3" << std::endl;//2
}

在 cppreference 的 documentation 字符串文字上实际上有一个完全相同情况的例子。

If a valid hex digit follows a hex escape in a string literal, it would fail to compile as an invalid escape sequence. String concatenation can be used as a workaround:

他们提供了以下示例:

// const char* p = "\xfff"; // error: hex escape sequence out of range
const char* p = "\xff""f";  // OK   : the literal is const char[3] holding {'\xff','f','[=10=]'}

应用他们对你的问题的解释,我们可以用两种方式打印字符串文字 be3

std::cout << "b\x65" "3" << std::endl;
std::cout << "b\x65" << "3" << std::endl;