0

这是我的代码:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{ 
    FILE *p;char c[79];
    clrscr();
    p = fopen("file1.dat","w");
    printf("\nenter lines and enter end1 to end ");
    scanf("%s",c);
    if (strcmp(c,"end1") != 0)
       do
       {  
           fputc('\n',p);
           fputs(c,p);
           gets(c);
       } while(strcmp(c,"end1")!=0);

    fclose(p);
    p = fopen("file1.dat","r");
    printf("lines in file:\n");
    while(!feof(p))
    {
        fgets(c,80,p);
        printf("%s\n",c);
    }
    fclose(p);
    return 0;
    getch();
}

我的问题是当我输入(并写入文件)时

hello
my name is abc

然后键入 end1 终止,当文件内容被读取和打印时,我得到的输出为

hello

my name is abc

为什么打印两个换行符而不是 1 个以及如何解决这个问题?

4

3 回答 3

1

当您第一次调用scanf换行符时,您键入的内容会被抛在后面。然后,您将显式换行符放入文件中,并调用gets(this is bad ),它会拾取第一个换行符,然后再次循环以打印另一个换行符。所以你得到两个。

如果您getchar()在 之后立即调用scanf,它将删除多余的换行符(只要您只键入一个单词然后回车)。例如

scanf("%s",c);
getchar();             // discard newline
if (strcmp(c,"end1") != 0)
   do
   {  
       fputc('\n',p);  // you probably want to switch these two lines
       fputs(c,p);     //
       gets(c);
   } while(strcmp(c,"end1")!=0);
于 2013-04-03T14:28:30.253 回答
1

请注意以下关于 fgets()....

fgets() 从流中最多读入一个小于 size 的字符,并将它们存储到 s 指向的缓冲区中。在 EOF 或换行符后停止读取。如果读取了换行符,则将其存储到缓冲区中。'\0' 存储在缓冲区中的最后一个字符之后。

鉴于您正在使用 fgets() 读取文件,然后使用 printf("%s\n", ... ) 打印文件,您将输出两个换行符。

于 2013-04-03T14:34:09.047 回答
0

字符串 sscanf'd 包含换行符,因为这是您输入的内容!

c[strlen(c)] = '\0'是一个粗略的修复,用额外的 null 替换最后的换行符

于 2013-04-03T14:29:37.780 回答