我想使用 printf 输出文本。
如果我想打印用户之前输入的文本并且可能包含%,则输出会是乱码。这可能是由于%printf 中的格式说明符,但没有给出值/参数。
例如:
std::string inputString = "% Test";
printf(inputString.c_str());
Output: 6.698271e-308st
Run Code Online (Sandbox Code Playgroud)
期望的输出是:% Test
有没有一种优雅的方法来避免这种情况?输入%%而不是%有效,但显然不太人性化。
我看到的唯一其他方法是修改输入字符串以自动将每个单个替换%为%%. 但这是要走的路吗?我特别想要/需要使用printf,但cout不可能使用
要么你用这个:
printf("%s", string.c_str());
Run Code Online (Sandbox Code Playgroud)
或者您使用根本不进行格式化的:
puts(string.c_str());
Run Code Online (Sandbox Code Playgroud)
请注意,这puts总是会添加换行符!
编辑:添加c_str以避免与实际问题混淆。