簡體   English   中英

scanf()和gets()的意外行為

[英]unexpected behavior of scanf() and gets()

我想用以下代碼一次性在文件中寫一行(包括空格):

//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." 

然后按Enter進入屏幕的陳述是

"do you want to write more"

到現在為止還不錯,但是當我輸入除'n'或'N'以外的鍵時(根據程序邏輯編寫更多行的要求),則該消息

"do you want to write more"

現在再次打印。如果我按'n'或'N'以外的其他鍵,則會在屏幕上打印同一行。

"do you want to write more"

4次,即字數,在這種情況下為4。通過這種不靈活的過程,我在文件上得到了所需的行,但是如果響應於第一次打印語句

"do you want to write more"

我按“ n”或“ N”,則只有第一個單詞(即本例中的“我”)會打印在文件上。 那么,一次就在文件上寫完整行的解決方案是什么?為什么在這種情況下,gets()和fputs()似乎無效? 比xxx提前。

做這樣的事情,它是一個非常粗糙的程序,但應該給你一個想法

您的錯誤,您僅在程序中創建了一個指向char的指針,您需要使用malloc為該指針分配內存,或者另一個選擇就是創建一個char數組。 我已經做了。

#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()是否將新行char保留在緩沖區中?

如果您使用

scanf("%s",ch);

(我假設這是“ scanf”的意思),這將讀取一個字符串。 如果您輸入

“我的名字叫巴安特。”

這將導致4個字符串:“ my”,“ name”,“ is”和“ bayant”。

請注意,根據您的描述,您不想讀取字符串,而是想要讀取lines 要使用scanf閱讀整行文本,可以使用:

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

這意味着:第1行:“閱讀所有內容,直到找到\\ n字符為止”。

第2行:“讀取並忽略該'\\ n'字符(留在緩沖區中)”。

我應該說這不是一個安全的解決方案,因為用戶很容易會溢出“ ch”緩沖區,但是我敢肯定,如果這是您的特殊情況,您可以找到更好的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM