gpt4 book ai didi

C++ 打印 : newline (\n) from commandline argument

转载 作者:太空狗 更新时间:2023-10-29 23:34:36 27 4
gpt4 key购买 nike

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

例子.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

最佳答案

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

关于C++ 打印 : newline (\n) from commandline argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2508796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com