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

2019-01-26 12:59发布

问题:

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 formatting.

How can I use printf (or cout I guess) to print '\n' instead of printing an actual newline? Do I just need to do some manual parsing for this?

EDIT: I'm receiving my data dynamically, it's not just the \n that I'm corned about, but rather all symbols. For example, this is my printf statement:

printf("%c", theChar);

How can I make this print \n when a newline is passed in as theChar but still make it print normal text when theChar is a valid printable character?

回答1:

Print "\\n" – "\\" produces "\" and then "n" is recognized as an ordinary symbol. For more information see here.



回答2:

The function printchar() below will print some characters as "special", and print the octal code for characters out of range (a la Emacs), but print normal characters otherwise. I also took the liberty of having '\n' print a real '\n' after it to make your output more readable. Also note that I use an int in the loop in main just to be able to iterate over the whole range of unsigned char. In your usage you would likely just have an unsigned char that you read from your dataset.

#include <stdio.h>

static void printchar(unsigned char theChar) {

    switch (theChar) {

        case '\n':
            printf("\\n\n");
            break;
        case '\r':
            printf("\\r");
            break;
        case '\t':
            printf("\\t");
            break;
        default:
            if ((theChar < 0x20) || (theChar > 0x7f)) {
                printf("\\%03o", (unsigned char)theChar);
            } else {
                printf("%c", theChar);
            }
        break;
   }
}

int main(int argc, char** argv) {

    int theChar;

    (void)argc;
    (void)argv;

    for (theChar = 0x00; theChar <= 0xff; theChar++) {
        printchar((unsigned char)theChar);
    }
    printf("\n");
}


回答3:

Just use "\\n" (two slashes)



回答4:

You can escape the backslash to make it print just a normal backslash: "\\n".

Edit: Yes you'll have to do some manual parsing. However the code to do so, would just be a search and replace.



回答5:

If you want to make sure that you don't print any non-printable characters, then you can use the functions in ctype.h like isprint:

if( isprint( theChar ) )
  printf( "%c", theChar )
else
  switch( theChar )
  {
  case '\n':
     printf( "\\n" );
     break;
  ... repeat for other interesting control characters ...
  default:
     printf( "\\0%hho", theChar ); // print octal representation of character.
     break;
  }


回答6:

printf("\\n");


回答7:

In addition to the examples provided by other people, you should look at the character classification functions like isprint() and iscntrl(). Those can be used to detect which characters are or aren't printable without having to hardcode hex values from an ascii table.



回答8:

In C/C++, the '\' character is reserved as the escape character. So whenever you want to actually print a '\', you must enter '\'. So to print the actual '\n' value you would print the following:

printf("\\n");


回答9:

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);
}


回答10:

As of C++11 you can also use raw strings

std::printf(R"(\\n)");

everything inside the R"( and )" will be printed literally. escape sequences will not be processed.



回答11:

There are three solutions for this question:

Solution 1: Every Symbol, Number, Alphabet has it's own ASCII value. The ASCII value of '\' as 92 and 'n' as 110. The immediate values(Numbers (ASCII)) are stored onto two integer variables. While printing, the format specifier %c (Character), is used.

void main() { 
    int i=92, j=110; 
    clrscr(); 
    printf("%c%c", i, j);
    getch();
}

Try it out in your C programming software...

Solution 2:

The programs works. But I think this one isn't fair... At the output screen, type the input as \n... you will get another \n..

void main() {
  char a[10];
  gets(a);
  printf("\n\n\n\n");
  puts(a);
  getch(); 
}

Try out the programs

Solution 3: Already said above use \n