如何将字符串文字中的特殊字符打印为 "backslash" 符号?

How to print special characters from string literal as their "backslash" symbol?

我有常规的字符串文字,想按原样打印它 - 原始,类似于 Python 中的 repr() 函数。


例如:

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

如何让 C 打印出来

this thing\n

而不是

this thing
 

完整解决方案:

#include <stdio.h>

int main () {
    printf("This thing\n");
    return 0;
}

您可以使用 "\n" 来打印 \n 您也可以将它与 \t 一起使用。

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

或者你可以这样做:

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

解决方案很少:

  1. \n前加上\,所以n前的反斜杠被识别为普通符号,因此n不包含在特殊符号中:printf("This thing\n");
  2. 如果您的编译器支持 GNU 扩展,请使用原始字符串:printf(R"(This thing\n)");
  3. 编写自己的函数:
void myRepr(const char* str)
{
    while (*str != '[=10=]') {
        switch (*str) {
            case '\n':
                fputs("\n", stdout);
                break;
            case '\t':
                fputs("\t", stdout);
                break;
            // case ...
            default:
                fputc(*str, stdout);
        }
        ++str;
    }
}