C++ printf:来自命令行参数的换行符(\n)

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)

Mic*_*yan 8

不,不要那样做!这是一个非常严重的漏洞.你永远不应该接受格式字符串作为输入.如果您想在看到"\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所建议的那样.

  • @Mark,你可能认为你有控制权......但是要等到它与一个来自组织的其他代码的庞大代码库结束.您是否知道追踪并防止其在其他地方结束会有多困难?最好不要让它始终进入你的代码库. (2认同)