-1
我在這裏有一個程序,允許用戶在其他功能之間追加一個文本文件,但我已經顯示了2以保持簡單。問題是,當用戶選擇時,說選項號。 1,「Append」&「輸入一個句子:」出現的很好,但程序退出,即在用戶輸入句子之前退出。我該如何解決 ? (我試過與工作,但在這裏我有一個文件的工作,但無法獲得所需的輸入scanf函數& printf語句一個簡單的例子!)C程序在接受輸入前退出
int main()
{
int choice;
char c[2000];
FILE *fp;
printf("Welcome to my Text Editor!\n");
printf("Enter the letter for the operation that you would like to carry out on the file\n");
printf("1 - Append a word to end of file\n");
printf("2 - Search for a word in the file\n");
scanf ("%d", &choice);
if (choice == 1)
{
printf ("Append\n");
fp=fopen("C:/Users/Asim/Desktop/random.txt","a");
if(fp==NULL){
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(c);
fprintf(fp,"%s",c);
fclose(fp);
}
else if (choice == 2)
{
printf ("Search");
}
else
{
printf ("Invalid choice!");
}
}
您的scanf將\ n保留在緩衝區中,將其替換爲getc或許將選項更改爲char? – Gar
這個問題的一些味道已經被問過千次之前,請問之前請做一些調查。也請不要使用get,那個函數過去17年已經過時了。你爲什麼從超過17年的來源學習C? – Lundin