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\non newline"
output is:
print this\non 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 “\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; }Or, if you are including the Boost C++ Libraries in your project, you can use the
boost::replace_allfunction to replace instances of “\\n” with “\n”, as suggested by Pukku.