Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 836
samoz Avatar asked Jul 03 '09 15:07

samoz


2 Answers

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

like image 85
sharptooth Avatar answered Nov 09 '22 12:11

sharptooth


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");
}
like image 20
Jared Oberhaus Avatar answered Nov 09 '22 11:11

Jared Oberhaus