C ++ printf:newline(\\\<br/>)from commandline argument [英] C++ printf: newline (\n) from commandline argument

查看:147
本文介绍了C ++ printf:newline(\\\<br/>)from commandline argument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打印格式字符串如何作为参数传递?

How print format string passed as argument ?

example.cpp:

example.cpp:

#include <iostream> 
int main(int ac, char* av[]) 
{
     printf(av[1],"anything");
     return 0;
}

尝试:

example.exe "print this\non newline"

输出为:

print this\non newline

而不是我想要的:

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 "\n", 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] != '\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 函数,用Pukku建议将\\\\
的实例替换为\\\

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 "\n", as suggested by Pukku.

这篇关于C ++ printf:newline(\\\<br/>)from commandline argument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆