【发布时间】:2018-05-11 04:51:06
【问题描述】:
我正在用 C 语言编写一个简单的练习应用程序,它应该询问用户是要写入文件还是读取文件。我想给文件命名,然后在控制台中输入一些文本。我想使用该文本将其保存到文件中。
问题是,当我已经为文件命名时,我无法将数据输入到控制台,因此我无法将这些数据保存到文本文件中。此外,while 循环会忽略我的 'y' 以再次重新启动程序。此外,当我想使用读取文件时,它确实可以,程序可以工作,但它也会添加默认指令(仅打印错误),但我不希望这样,只需从文件中读取并将其打印到控制台。
谁能解释我做错了什么以及如何解决这个问题?我将不胜感激。
这是我的代码:
int main()
{
FILE *file;
char nameFile[32];
char string[500];
char ans[2];
int choice;
do{
printf("What do you want to do?\n");
printf("1. Write text to file\n");
printf("2. Read text file\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Give name to the file (*.txt).\n");
scanf("%s", nameFile); //This line skips me to line where program ask user if restart the program (I have no idea why :()
system("clear");
file=fopen(nameFile, "w");
if(file!=NULL){
printf("Input text:\n");
scanf("%[^\n]", string); //<--- HERE I'cant input text to console, seems like scanf doesn't work.
fprintf(file, "%s", string);
printf("\n\t\t\t-----------Ended writing.------------\n");
fclose(file);
}
else
{
printf("Could not open the file.");
return -1;
}
break;
case 2:
printf("Give name to the file (*.txt)");
scanf("%s", nameFile);
system("clear");
file=fopen(nameFile, "r");
if(file!=NULL){
while (!feof(file)) {
fscanf(file, "%s", string);
printf("%s\n",string); //After printing data from text file, adds instruction from line , and that is printing Error. How to get rid of it?
}
}
else{
printf("Could not open the file.");
return -1;
}
default:
printf("Error.");
break;
}
printf("Do you want to restart the program? (y/*)"); //Even if I write 'y', program ends anyway :(
scanf("%s", ans);
}
while(ans=='y');
return 0;
}
【问题讨论】:
-
你错过了休息时间;案例 2 末尾的语句。这就是我更喜欢 if 语句的原因之一。
-
我真的忘记了 - 谢谢,终于不再打印错误了。
标签: c input while-loop switch-statement file-writing