2011-12-24 52 views
2

我可能错过了一些显而易见的东西,但是每次我写入文件时,输入的文本都在打开文档的第二行时显示。这是什么造成的?当我写入文件时 n来自哪里?

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

回答

4

你告诉scanf不要吃任何\n字符,所以仍然会有一个坐在输入缓冲区,当你开始用putcgetchar循环。

一个解决方案是用一个呼叫环路先于putcgetchar\n

+0

这将是在putc将调用的参数删除\ n ? – bqui56 2011-12-24 19:53:12

+0

@ stariz77:对不起,这是一个错字。我的意思是'getchar'。 – 2011-12-24 19:55:14

0

因为scanf没有使用'\n'(或'\t')。

尝试用标签指定文件名:"filename<TAB>first line<ENTER>" :)


为了摆脱ENTER,使用

while ((ch = getchar()) != '\n' && ch != EOF) /* void */; 
if (ch == EOF) /* no more input; abort or whatever */;