How to print '\ n' instead of a new line?

I am writing a program that uses the hexadecimal dump dumps of its input. However, I ran into problems wrapping lines, tabs, etc. And destruction of output formatting.

How can I use printf (or cout, I think) to print '\ n' instead of printing the actual new line? Do I just need to disassemble manually for this?

EDIT: I get my data dynamically, it's not only \ n that I fixed, but all the characters. For example, this is my printf statement:

printf("%c", theChar);

How can I print this \ n when a newline is passed as Char, but still makes it print plain text when Char is a valid printable character?

+6
source share
11 answers

Printing "\\ n" - "\\" creates "\" and then "n" is recognized as a regular character. For more information see here .

+36
source

printchar() "" (a la Emacs), . '\n' '\n' , . , int main, unsigned char. , , unsigned char, .

#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");
}
+22

"\\n" ( )

+8

, : "\\n".

: , . .

+6

, , ctype.h 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;
  }
+5
printf("\\n");
+4

, , , isprint() iscntrl(). , ascii.

+3

C/++ '\' escape-. , '\', '\'. , "\n", :

printf("\\n");
+3

String:: replace, printf.

printf, - :

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

... , .

[] , :

void printfNeat(char* str, ...)
{
    va_list argList;
    va_start(argList, msg);

    string tidyString(str);
    tidyString.replace("\n", "\\n");
    vprintf(tidyString, argList);

    va_end(argList);
}
+1

++ 11

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

R"( )" . escape- .

+1

:

1: , , ASCII. ASCII "\" 92 "n" 110. ( (ASCII)) . % c ().

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

C...

2:

. , ... \n... \n..

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

3: \n

-2

All Articles