Seb*_*btm 2 c++ string formatting printf newline
打印格式字符串如何作为参数传递?
example.cpp:
#include <iostream>
int main(int ac, char* av[])
{
printf(av[1],"anything");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试:
example.exe "print this\non newline"
Run Code Online (Sandbox Code Playgroud)
输出是:
print this\non newline
Run Code Online (Sandbox Code Playgroud)
相反,我想:
print this
on newline
Run Code Online (Sandbox Code Playgroud)
不,不要那样做!这是一个非常严重的漏洞.你永远不应该接受格式字符串作为输入.如果您想在看到"\n"时打印换行符,更好的方法是:
#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[])
{
if ( argc != 2 ){
std::cerr << "Exactly one parameter required!" << std::endl;
return 1;
}
int idx = 0;
const char* str = argv[1];
while ( str[idx] != '\0' ){
if ( (str[idx]=='\\') && (str[idx+1]=='n') ){
std::cout << std::endl;
idx+=2;
}else{
std::cout << str[idx];
idx++;
}
}
return 0;
}
或者,如果您在项目中包含Boost C++库,则可以使用该boost::replace_all函数将"\\n"的实例替换为"\n",如Pukku所建议的那样.
| 归档时间: |
|
| 查看次数: |
13380 次 |
| 最近记录: |