2014-03-07 35 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