-1

I want to write this program which takes user input for filename and also the string input to write the data into the file.

The program successfully takes file name as input but when it takes the string to be written as input it just skips it and completes execution

#include <conio.h>      
int main()
{
   FILE *filepointer;
   printf("Enter file name with extension:\n");
   char name[100];
   scanf("%s",&name);
   filepointer = fopen(name,"w");  
   char str[1024];
   printf("Enter what you want to write\n");
   gets(str); //This is not taking input
   fprintf(filepointer,"%s",str);
 
   return 0;
}```
  • https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer – pm100 Jul 23 '22 at 21:01
  • Although this is not the reason for your problem, I strongly suggest that you use `fgets` instead of `gets`. See this question for the reason why I suggest this: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/12149471) – Andreas Wenzel Jul 23 '22 at 23:18

1 Answers1

1

Your program will work as you intend to if you include the stdio.h header file at the start of your program. This is necessary because the functions in this program and the struct FILE are declared there. You must also write at the end of the program this line of code:

fclose(filepointer);

This will ensure that the changes to the file will remain after the execution of the program.

Regarding the line

gets(str);

the problem is that the button ENTER which has been pressed from the previous input ( fileName prompt ) is still on the buffer. So when the line

gets(str);

is executed it doesn't let you enter anything because the gets function reads until it finds '\n' but in this case this is the first thing that it reads. The solution I came up with is the following:

#include <conio.h>  
#include <stdio.h>    
int main()
{
   FILE *filepointer;
   printf("Enter file name with extension:\n ");
   char name[100];
   scanf("%s",&name);
   filepointer = fopen(name,"w");  
   char str[1024];
   getchar();
   printf("Enter what you want to write:\n ");
   gets(str); //This is not taking input
   fprintf(filepointer,"%s",str);
   fclose(filepointer);
   return 0;
}
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • `getchar()` will only read a single character, which is not necessarily the newline character. If you want to read everything up to and including the newline character, then `int c; do { c = getchar(); } while ( c != EOF && c != '\n' );` would be better. The lines `scanf( "%*[^\n]" ); getchar();` would have the same effect. – Andreas Wenzel Jul 23 '22 at 23:10