有人能解释一下文件处理中的错误吗?



我正在编写一个程序,该程序将学生记录存储在桌面名为'new'的文件中。如果没有名为"new"的文件,那么它应该首先创建它,所以我使用了If语句。我还把整个代码放在一个do while循环中,所以它应该一次又一次地循环代码。在do中,我使用了switch

  1. 使用fprintf

  2. 写入文件
  3. 代码仍未编写(稍后将添加read函数)

  4. 退出do while循环

但是我得到一个错误'ch' undeclared (first use this fucntion)

如何修复这个程序?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct
{
int *name;
int score;
}structure;
int main()
{
FILE *file= fopen("C://Users//Abhimanyu Aryan//Desktop//new.txt","r");
if(file==NULL)
{
FILE *file=fopen("C://Users//Abhimanyu Aryan//Desktop//new.txt","w");
}
//Loop through this
do
{
printf("n1) Add recordn2) View Recordn3) Exit");
int ch;
printf("Enter your choice: ");
scanf("%i",&ch);
switch (ch)
{
    //case 1 will include write access to file on pressing 1
case 1:
    //name
    printf("Enter name: ");
    char name[30];
    scanf("%c", name);
    //score
    printf("Enter score: ");
    int score;
    scanf("%i", &score);
    //printing to file
    fprintf(file, "%ct%i", name, score);
    break;
//case still not in use
case 2:
    break;
//case to exit
case 3:
    break;
}
}while(ch != 3);
fclose(file);
return 0;
}

啊…问题很可能出在这行代码上:

} while (ch != 3)

ch变量在do-while循环中定义ONLY…我试着在循环外定义它看看是否有帮助

应该在do. while循环之外初始化ch,这就是错误

最新更新