格式化与未格式化的字符串C.

时间:2016-10-04 11:52:38

标签: c string

我有char * temp_string我保留这些字符:Hello\nWor'ld\\\042最后包括\0

这是我制作字符串的方式:

char * addDataChunk(char * data,char c)
{
    char * p;
    if(data==NULL)
    {
        if(!(data=(char*)malloc(sizeof(char)*2))){
            printf("malloc error\n");
            throwInternError();
        }
        data[0]=c;
        data[1]='\0';
        return data;
    }
    else
    {
        if((p = (char*)realloc(data,((strlen(data)+2)*sizeof(char))))){
            data = p;
        }
        else{
            printf("realloc error\n");
            throwInternError();
        }
        data[strlen(data)+1] = '\0';
        data[strlen(data)] = c;
        return data;
    }
}

这就是我使用addDataChunk的方式:

temp_char =getc(pFile);
temp_string=addDataChunk(temp_string,temp_char);

当我这两行时:

printf("%s\n","Hello\nWor'ld\\\042");
printf("%s\n",temp_string);

我明白了:

Hello
Wor'ld\"
Hello\nWor'ld\\\042

有人知道为什么输出不同吗?

2 个答案:

答案 0 :(得分:2)

您的texte文件包含

  

您好\ nWor'ld \\ 042

现在,如果您逐字逐句地阅读此文件getc,您将逐字逐字地获取这些字符,这意味着您将连续获得:

Hello\n,...,{ {1}},\\\04

另一方面,string literal 2将由编译器转换为:

"Hello\nWor'ld\\\042"Hello,...,\n,{ {1}}。

实际上\会被翻译成ASCII字符10(换行符),"会被翻译成\n\\会被翻译成ASCII字符,其中八进制中的值是042,即\

您应该阅读escape sequences

答案 1 :(得分:-2)

请使用此:

char* temp_string = "Hello\n world\\\042";
printf(" %s","Hello\nworld\\\042\n");
printf("%s",temp_string);
相关问题