strcat函数中“ \ n”和“ \ n”有什么区别?

时间:2019-01-04 15:01:38

标签: c

对不起,我英语不好, 我制作了一个从File1读取行并将其向后打印到File2的程序 在File1中,所有行的末尾都有\ n,最后一行除外。它不必是雪人。如果我只是在最后一行中没有strcat \ n的情况下运行程序,则输出File2将显示为底部。因此,我尝试将\ n strcat到该进程的最后一行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;
}

2 个答案:

答案 0 :(得分:0)

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

microbenchmark::microbenchmark( for.set.2cond = fun1(copy(DT)), for.set.ind = fun2(copy(DT)), for.get = fun3(copy(DT)), for.SDcol = fun4(copy(DT)), for.list = fun5(copy(DT)), for.set.if =fun6(copy(DT)) ) #> Unit: microseconds #> expr min lq mean median uq max neval cld #> for.set.2cond 59.812 67.599 131.6392 75.5620 114.6690 4561.597 100 a #> for.set.ind 71.492 79.985 142.2814 87.0640 130.0650 4410.476 100 a #> for.get 553.522 569.979 732.6097 581.3045 789.9365 7157.202 100 c #> for.SDcol 376.919 391.784 527.5202 398.3310 629.9675 5935.491 100 b #> for.list 69.722 81.932 137.2275 87.7720 123.6935 3906.149 100 a #> for.set.if 52.380 58.397 116.1909 65.1215 72.5535 4570.445 100 a 是一个字符串常量,包含"\n"字符,后跟一个终止于该字符串的空字节,类型为\n,而const char []是字符{{1} },类型为'\n'(所有字符常量也是如此)。

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

答案 1 :(得分:0)

char * strcat ( char * destination, const char * source );

接受const char *参数,就像“ \ n”是..一样,但是'\ n'只是char类型的

相关问题