C++ printf: newline () from commandline argument(C ++ printf:命令行参数的换行符( n))
问题描述
打印格式字符串如何作为参数传递?
example.cpp:
#include <iostream>int main(int ac, char* av[]){printf(av[1],"任何东西");返回0;}尝试:
example.exe "打印此非换行符"输出是:
打印此非换行符我想要:
打印这个在换行符上解决方案不,不要那样做!这是一个非常严重的漏洞.您永远不应该接受格式字符串作为输入.如果您想在看到 "时打印一个换行符,更好的方法是:
<上一页>#include <iostream>#include <cstdlib>int main(int argc, char* argv[]){如果(argc!= 2){std::cerr <<只需要一个参数!"<<标准::endl;返回 1;}int idx = 0;const char* str = argv[1];而 ( str[idx] != ' ' ){if ( (str[idx]=='\') && (str[idx+1]=='n') ){std::cout <<标准::endl;idx+=2;}别的{std::cout <<str[idx];idx++;}}返回0;}
或者,如果您在项目中包含 Boost C++ 库,则可以按照建议使用 boost::replace_all 函数将\n"的实例替换为
"由 Pukku 提供.
How print format string passed as argument ?
example.cpp:
#include <iostream>
int main(int ac, char* av[])
{
printf(av[1],"anything");
return 0;
}
try:
example.exe "print this
on newline"
output is:
print this
on newline
instead I want:
print this
on newline
No, do not do that! That is a very severe vulnerability. You should never accept format strings as input. If you would like to print a newline whenever you see a " ", a better approach would be:
#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] != ' ' ){
if ( (str[idx]=='\') && (str[idx+1]=='n') ){
std::cout << std::endl;
idx+=2;
}else{
std::cout << str[idx];
idx++;
}
}
return 0;
}
Or, if you are including the Boost C++ Libraries in your project, you can use the boost::replace_all function to replace instances of "\n" with "
", as suggested by Pukku.
这篇关于C ++ printf:命令行参数的换行符( n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++ printf:命令行参数的换行符( n)
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
