How to print '\n' instead of a newline?

前端 未结 11 595
南方客
南方客 2020-12-11 04:34

I am writing a program that uses prints a hex dump of its input. However, I\'m running into problems when newlines, tabs, etc are passed in and destroying my output formatti

11条回答
  •  误落风尘
    2020-12-11 04:58

    Just use String::replace to replace the offending characters before you call printf.

    You could wrap the printf to do something like this:

    void printfNeat(char* str)
    {
        string tidyString(str);
        tidyString.replace("\n", "\\n");
        printf(tidyString);
    }
    

    ...and just add extra replace statements to rid yourself of other unwanted characters.

    [Edit] or if you want to use arguments, try this:

    void printfNeat(char* str, ...)
    {
        va_list argList;
        va_start(argList, msg);
    
        string tidyString(str);
        tidyString.replace("\n", "\\n");
        vprintf(tidyString, argList);
    
        va_end(argList);
    }
    

提交回复
热议问题