C++ printf: newline (\n) from commandline argument

前端 未结 7 1793
刺人心
刺人心 2020-12-20 02:07

How print format string passed as argument ?

example.cpp:

#include  
int main(int ac, char* av[]) 
{
     printf(av[1],\"anything\");         


        
7条回答
  •  不思量自难忘°
    2020-12-20 03:01

    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 
    #include 
    
    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;
    }
    

    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.

提交回复
热议问题