我有一个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


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

最佳答案

您的texte文件包含


  您好\ n世界\\ 042


现在,如果使用getc逐个字符地读取此文件,则将逐字读取字符,这意味着您将依次得到:

Hello\n,...,\\\0,,4

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

"Hello\nWor'ld\\\042"Hello,...,\n\

实际上,"将转换为ASCII字符10(换行),\n将转换为\\,而\将转换为ASCII字符,其八进制值为042,即\042

您应该阅读有关escape sequences的信息。

关于c - 格式化与未格式化的字符串C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39851594/

10-10 16:22
查看更多