2014-03-07 37 views
0

我想写一本线(包括空格)的文件中的一个去与下面的代码: - 上面代码的意外的行为,并得到()

//in main 
char ch[40]; 
FILE *p; 
char choice; 
p=fopen("textfile.txt","w"); 
printf("%s\n","you are going to write in the first file"); 
while (1) 
{ 
    gets(ch);// if i use scanf() here the result is same,i.e,frustrating 
    fputs(ch,p); 
    printf("%s\n","do you want to write more"); 
    choice=getche(); 
    if (choice=='n'|| choice=='N') 
    { 
     break; 
    } 
} 

结果是令人沮丧的我,很难解释,但我仍然会尝试。 如果我进入,比如说,

"my name is bayant." 

并按进入statment说到屏幕

"do you want to write more" 

是好到现在,但是当我prees的关键除了“n”或“N '(所要求的程序来写多行的逻辑),则该消息

"do you want to write more" 

打印again.Now如果我按比其他键‘n’或‘N’上但屏幕程序的同一行的打印跟随并打印声明

"do you want to write more" 

4倍,这是词的数量,即4在此case.By下面这个呆板过程我得到想要的行上我的文件,但如果响应于声明的第一次印刷

"do you want to write more" 

我按“n”或“N”,那么只有第一个单词,即“我的”在这种情况下打印在文件上。 那么解决方案是一次性在文件上写出完整的一行?为什么在这种情况下get()和fputs()似乎无效? thanxxx提前。

+1

希望得到()'因为C11 – Manu343726

+0

得到()缓冲区溢出天堂!!否则请不要使用gets,反而使用fgets。在Windows使用gets_s() – tesseract

+0

@tesseract我知道它,但即使我使用scanf()问题仍然存在。 – YakRangi

回答

2

做这样的事情,它是一个非常粗略的计划,但应该给你一个想法

你的错误,你就只能做一个指向程序中的一个字符,你需要使用malloc的指针分配内存,或者其他选项只是创建一个字符数组。我已经完成了。

#include <stdio.h> 
#include <stdlib.h> 
int main(void){ 

char ch[100]; 
FILE *p; 
char choice; 
p=fopen("textfile.txt","w"); 
printf("%s\n","you are going to write in the first file"); 
while (1) 
{ 
// gets(ch);// if i use scanf() here the result is same,i.e,frustrating 
int c =0; 

fgets(ch,100,stdin); 
fputs(ch,p); 
printf("%s\n","do you want to write more"); 
choice=getchar(); 
if (choice=='n'|| choice=='N') 
    { 
    break; 
    } 
while ((c = getchar()) != '\n' && c != EOF); 
} 
return 0; 
} 

你程序重复printf("%s\n","do you want to write more");因为输入缓冲区有\ n写入到它,你需要阅读之前清除缓冲区。这条线将删除缓存换行符while ((c = getchar()) != '\n' && c != EOF);

检查这个 scanf() leaves the new line char in buffer?

+0

使用'unsigned int c = 0;'而不是'int c = 0;'的任何特定原因? – chux

+0

废话我的坏,应该是int。忘了eof.edited – tesseract

+1

我怀疑'unsigned int c'也会起作用。 'c!= EOF'会将EOF强制转换为'unsigned'并且按照预期执行。不是我推荐'unsigned int c',只是认为它是新颖的。 – chux

2

如果使用

scanf("%s",ch); 

(我以为是你所说的“scanf函数”的意思),这将读取一个字符串。如果你输入

“我的名字是bayant。”

这将导致4个字符串:“我的”,“名称”,“是”和“bayant。”。

请注意,从您的描述中,你不想读取字符串,你想要读取。读取与scanf的文字一整行,你可以使用:

scanf("%[^\n]", ch); 
scanf("%*c"); 

这意味着: 第1行:“直到你找到一个\ n字符阅读一切”。

第2行:“读取并忽略'\ n'字符(它留在缓冲区中)”。

我应该说这不是一个安全的解决方案,因为用户可以很容易地溢出“ch”缓冲区,但我相信你可以找到更好的方法来做到这一点,如果这是你的特定情况下真正的问题。

+1

如果使用'scanf()',建议'if(1 == scanf(“%39 [^ \ n]%* c”,ch))Success();' – chux