I’m probably missing something obvious, but every time I write to a file, the inputted text is on the second line of the document when I open it. What is causing this?
#include <stdio.h>
int main()
{
char c;
char filename[100];
FILE *fp;
printf("Type the name of the file to write to followed by enter: \n\n");
scanf("%[^\t\n]s", filename);
fp = fopen(filename, "w");
printf("\n\nEnter the text you wish to write to this file: \n\n");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
return 0;
}
You’ve told
scanfnot to eat any\ncharacters, so there will still be one sitting in the input buffer when you start the loop withputcgetchar.One solution would be to precede the loop with a call to
putcgetcharto eat the\n.