Вопрос

I'm having a little trouble with the code below and I can not for the life of me figure out what went wrong and why it is displaying what it does, any help or assistance would be most appreciated. It is supposed to allow 5 lines of text to be entered and display those 5 lines onscreen, however it only allows 4 lines to be entered, and 4 are displayed. Please help!

#include <stdio.h>

int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
scanf("%s",filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
    printf("unable to open File");
}
for(n=1;n<6;n++)
{
    printf("\nEnter line %d:",n+1);
    gets(string);
    fputs(string,fp);
    fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
    printf("unable to open File");
}
for(n=1;n<6;n++)
{
    fgets(string,100,fp);
    printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}
Это было полезно?

Решение 2

Here is the modified code. Added gets instead of scanf and added return 0; if file is not opened.

#include <stdio.h>

int main()
{
char string[100];
char filename[20];
int n=0;
FILE *fp;
printf(" Enter the name of file to open ");
gets(filename);
fp =fopen(filename,"wr");
if(fp==NULL)
{
    printf("unable to open File");
    return 0; // do not proceed
}
for(n=1;n<6;n++)
{
    printf("\nEnter line %d:",n);
    gets(string);
    fputs(string,fp);
    fputs("\n",fp);
}
fclose(fp); /*close the file*/
fp =fopen(filename,"r");
if(fp==NULL)
{
    printf("unable to open File");
    return 0; // do not proceed
}
for(n=1;n<6;n++)
{
    fgets(string,100,fp);
    printf("%s",string);
}
fclose(fp); // close after reading.
return 0;
}

Другие советы

The problem is that scanf("%s", filename); doesn't consume the newline after the filename. So your first call to gets() reads this newline as an empty line.

Add:

gets(string);

after that line to use up the rest of the line before you start reading input lines.

replace scanf("%s",filename) with gets(filename)

To get rid of the newline in the buffer right after your call to scanf, you can simply add getchar();:

scanf("%s", filename); 
getchar();

But do adjust your for loops to start at 0, since you add 1 to n i.e:

for(n=0;n<6;n++)
      ^

After making those changes I was able to input 6 lines and then print all of them out.

As you've noticed, buffered input can be pesky if you don't deal with it properly as it can be inserted in your subsequent input calls. Don't be tempted to flush the stdin.

Here are some recommended alternatives on how to deal with this.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top