开发者

How to add a new line in a text file?

I have a few lines of code:

strcat(myTxt,"data");
strcat(myTxt,"\n");
strcat(myTxt,"data1");

In between the lines 开发者_JAVA百科I've done strcat of "\n"; however, when I do a write to a text file the "\n" is ignored and all the strings are concatenated as datadata1. How can I work around this issue?


This code works for me:

#include <string.h>
#include <stdio.h>

int main ()
{
    char myTxt[100];

    myTxt[0] = 0;
    strcat(myTxt, "data");
    strcat(myTxt, "\n");
    strcat(myTxt, "data1");

    printf("%s\n", myTxt);
    return 0;
}

Did you initialize the buffer's first byte? Edit: works also with a file as output:

#include <string.h>
#include <stdio.h>

int main ()
{
    char myTxt[100];
    FILE *out = fopen("out.txt", "wt");

    myTxt[0] = 0;
    strcat(myTxt, "data");
    strcat(myTxt, "\n");
    strcat(myTxt, "data1");

    fprintf(out, "%s\n", myTxt);
    fclose(out);
    return 0;
}


For file output, you should do strcat of "\r\n"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜