-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