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

C++ printf: newline () from commandline argument(C ++ printf:命令行参数的换行符( n))

本文介绍了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)

基础教程推荐