-1

I have regular string literal and want to print it as it is - raw, similar how repr() function in Python does.


For example:

char* text = "this thing\n";
printf("%s", text);

How do I get C to print

this thing\n

instead of

this thing
 
Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
cdpp
  • 152
  • 2
  • 9
  • 1
    Your question seems to have nothing to do with the repr special method in Python, could you either elaborate on the repr relationship or take it out of the title? – Andrew Holmgren Jul 20 '20 at 21:11

3 Answers3

2

There are few solutions:

  1. Prepend \n with \, so backslash before n is recognized as normal symbol, and therefore n isn't included to special symbol: printf("This thing\\n");
  2. If your compiler supports GNU extensions, use raw string: printf(R"(This thing\n)");
  3. Write own function:
void myRepr(const char* str)
{
    while (*str != '\0') {
        switch (*str) {
            case '\n':
                fputs("\\n", stdout);
                break;
            case '\t':
                fputs("\\t", stdout);
                break;
            // case ...
            default:
                fputc(*str, stdout);
        }
        ++str;
    }
}
Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
0

Full solution:

#include <stdio.h>

int main () {
    printf("This thing\\n");
    return 0;
}
AnthonyHein
  • 131
  • 4
  • 1
    The question is not completely clear, but I would imagine that although the input string is hard-coded as a constant in this example, it is intended as a more general question about how to convert a string containing newlines, rather than simply a question of how to hard-code a literal backslash. – alani Jul 20 '20 at 21:08
0

You can use "\\n" to print \n u can also use it with \t.

int main(){
    char* text = "this thing\\n";
    printf("%s", text);
}

or you can do it like this:

#include <stdio.h>
#include <string.h>

void newline(char* str){
    int i;
    for(i=0; i<strlen(str); i++){ // iterate through the string
        // 10 == the ascii code for new line
        if(str[i] != 10){ 
            printf("%c", str[i]);
        }
        else if (str[i] == 10){
            printf("\\n");
        }
    }
}

void newline2(char* str){ // same function useing in line if
    int i;
    for(i=0; i<strlen(str); i++){
        str[i] != 10 ? printf("%c", str[i]) : printf("\\n");
    }
}

int main(){
    char* text = "this \n thing\n";
    newline(text);
    newline2(text);
}
tibi
  • 186
  • 3
  • 11