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

前端 未结 7 1790
刺人心
刺人心 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 02:56

    At least if I understand correctly, you question is really about converting the "\n" escape sequence into a new-line character. That happens at compile time, so if (for example) you enter the "\n" on the command line, it gets printed out as "\n" instead of being converted to a new-line character.

    I wrote some code years ago to convert escape sequences when you want it done. Please don't pass it as the first argument to printf though. If you want to print a string entered by the user, use fputs, or the "%s" conversion format:

    int main(int argc, char **argv) { 
        if (argc > 1) 
            printf("%s", translate(argv[1]));
        return 0;
    }
    

提交回复
热议问题