gpt4 book ai didi

c - strcat函数中 "\n"和 '\n'有什么区别?

转载 作者:行者123 更新时间:2023-11-30 19:28:22 26 4
gpt4 key购买 nike

抱歉我的英语不好,我编写了一个程序,从 File1 读取行并将其向后打印到 File2在 File1 中,除了最后一行之外,所有行的末尾都有\n 它不一定是雪人。如果我只是在最后一行中运行没有 strcat\n 的程序,则输出 File2 显示为底部。所以我尝试在该过程中 strcat\n 到最后一行 strcat(buffer[9], "\n");有效,但是 strcat(buffer[9], '\n');不是。为什么会发生这种情况?

// FILE 1
Do you wanna build a snowman?\n
Come on lets go and play\n
I never see you anymore\n
Come out the door\n
It's like you've gone away-\n
We used to be best buddies\n
And now we're not\n
I wish you would tell me why!-\n
Do you wanna build a snowman?\n
It doesn't have to be a snowman.

// FILE 2
It doesn't have to be a snowman.Do you wanna build a snowman?\n
I wish you would tell me why!-\n
And now we're not\n
We used to be best buddies\n
It's like you've gone away-\n
Come out the door\n
I never see you anymore\n
Come on lets go and play\n
Do you wanna build a snowman?\n


include <stdio.h>
include <string.h>
define LINE 50

int main(int argc, char *argv[])
{

if (argc < 3)
{
puts("Usage : hw9 inputFileName OutputFileName");
exit(1);
}


FILE *fp, *fp2;
fp = fopen(argv[1],"r");
fp2 = fopen(argv[2], "w");
char *buffer[15][LINE];
char *buffer2[15];


if(fp == NULL || fp2 == NULL)
{
printf("File open error! \n");
return 1;
};

int i = 0;
while (fgets(buffer[i],LINE,fp)!=NULL)
{
buffer2[10-i] = buffer[i];
printf("buffer2[%d] : %s\n", 10-i, buffer2[10-i]);

i++;
}

working!
strcat(buffer[9], "\n");

error! why?
//strcat(buffer[9], '\n');

fprintf(fp2, buffer2[1]);


for (int i = 2; i <= 10; ++i)
fprintf(fp2, buffer2[i]);

fclose(fp);
fclose(fp2);

return 0;
}

最佳答案

在 C 语言中,双引号用于表示字符串常量,而单引号表示单个字符。

"\n" 是一个字符串常量,包含 \n 字符,后跟终止字符串的空字节,类型为 const char [],而 '\n' 是字符 \n 并且具有 int 类型(所有字符常量也是如此)。

strcat 函数需要一个 const char * 作为第二个参数。像 "\n" 这样的字符串常量符合条件,因为数组(在大多数情况下)会衰减为指向第一个元素的指针。传递 '\n' 确实不起作用,因为您将 int 传递给需要指针的函数。这会导致 \n 的编码值被视为 strcat 尝试取消引用的指针,调用 undefined behavior .

关于c - strcat函数中 "\n"和 '\n'有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com