假设我有一个十六进制字符串,我从一组字节计算出来,采用适合我的特定格式:
std::string s("#00ffe1");
Run Code Online (Sandbox Code Playgroud)
而且我不能签署它到std :: cout
std::cout << s;
//prints:
#00ffe1
Run Code Online (Sandbox Code Playgroud)
虽然我喜欢cout的工作方式,但为了我的目的,它更容易使用fprintf,因为这是输出一个更容易使用的格式化字符串fprintf.
我去写相同的字符串fprintf:
fprintf(stdout,"foo=%s",s);
// outputs:
G* // (i.e., nonsense)
Run Code Online (Sandbox Code Playgroud)
如何使用输出此字符串fprintf?
std::string是一个类,而不是"字符串",因为该术语适用于C(fprintf来自).该%s格式说明需要一个指向的一个空终止阵列char [].使用std::string方法c_str()返回空值终止字符串,并通过该到fprintf:
fprintf(..., s.c_str());
Run Code Online (Sandbox Code Playgroud)