S Raghav
S Raghav

Reputation: 1526

file output has two newline characters instead of one

This is my code:

#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();
}

My problem is that when I type (and write in the file)

hello
my name is abc

and then type end1 to terminate and when file contents are read and printed i get the output as

hello

my name is abc

Why are two newlines printed instead of 1 and how to solve this problem?

Upvotes: 0

Views: 186

Answers (3)

teppic
teppic

Reputation: 8195

When you first call scanf the newline you type is left behind. You then put an explicit newline into the file, and call gets (this is bad), which picks up the first newline, then loops again to print another. So you get two.

If you call getchar() immediately after scanf, it will remove the extra newline (as long as you only type one word followed by enter). e.g.

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);

Upvotes: 1

K Scott Piel
K Scott Piel

Reputation: 4380

Note the following regarding fgets()....

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

Given you are reading the file with fgets() then printing the file with printf( "%s\n", ... ) you are outputting two newlines.

Upvotes: 1

Vorsprung
Vorsprung

Reputation: 34327

the string sscanf'd includes a newline because that's what you typed in!

c[strlen(c)] = '\0' is a crude fix, replace the newline at the end with an extra null

Upvotes: 0

Related Questions