How to print '\n' instead of a newline?
Asked Answered
B

11

7

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?

Betimes answered 3/7, 2009 at 15:2 Comment(1)
Bear in mind that there is no way a single call to printf("%c", foo) can output \n, a string of two characters. You basically have to choose between altering the input (replacing "\n" with "\\n") or a good old fashioned if (theChar == '\n').Arboreal
F
40

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

Fib answered 3/7, 2009 at 15:4 Comment(0)
A
23

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");
}
Apatite answered 3/7, 2009 at 15:15 Comment(3)
Should be < 32 (or 0x20) and >= 127. Also for %o you need to cast theChar to unsigned char (or & 0xff) since char is usually signed.Chibchan
Thanks @mark4o, you're right about the 0x20 and the 32. Fixed my answer.Apatite
the condition for upper bound should be >= 0x7f instead of > 0x7f. 0x7f character represents delete which is non-printable characterFaker
W
8

Just use "\\n" (two slashes)

Ward answered 3/7, 2009 at 15:4 Comment(0)
M
6

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.

Maidenhead answered 3/7, 2009 at 15:4 Comment(0)
E
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;
  }
Endoparasite answered 3/7, 2009 at 17:22 Comment(0)
B
4
printf("\\n");
Bier answered 3/7, 2009 at 15:6 Comment(0)
S
3

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.

Samuella answered 3/7, 2009 at 22:29 Comment(0)
L
3

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");
Lipid answered 4/7, 2009 at 5:44 Comment(0)
C
1

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);
}
Cantlon answered 3/7, 2009 at 15:8 Comment(1)
This is not how std::basic_string::replace works. From en.cppreference.com/w/cpp/string/basic_string/replace we see that replace will replace the part of the string indicated by either [pos, pos + count) or [first, last) with a new string. It does not search for the original string and replace found occurrences.Sanson
M
1

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.

Mullens answered 11/7, 2014 at 0:46 Comment(0)
K
-2

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

Knott answered 3/6, 2012 at 3:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.