gpt4 book ai didi

c - 制作简单的设置文件时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:08 25 4
gpt4 key购买 nike

一些背景故事
我是一名工科学生(一年级),我们必须创建一个程序来管理学生名单。基本上将学生的信息放在一个结构数组中(学生姓名、出生日期、成绩)。必须可以添加学生、删除学生、对学生进行排序、更改信息、添加成绩、保存进度、加载进度和生成分数列表 (html/css)。

我的问题
我想为我的项目添加设置。我将一些信息放在一个名为 settings.txt 的文件中。第一行和第二行是整数,可以是 1 或 0。第三行是字符串。创建这个文件并从文件中读取工作正常,但我当然希望用户也能够更改他的设置。但是,当我运行下面的代码时,我的 .exe 崩溃了。这可能是因为我在做一些愚蠢的事情,但我已经看了几个小时了,我的“修复”让事情变得更糟。我希望有人能帮助我,在此先感谢! :)
我尝试添加一些英文注释,最初 printf 中的输出是荷兰语。有什么不明白的请追问!

代码

char getBool (char option[], char booly[]) {
if (option[0]!='0') {
strcpy(booly,"true");
} else {
strcpy(booly,"false");
}
}

char editSettings (char settings[], char startLoad[]) {
//This function will allow the user to edit some settings
//Declare variables: file: filename, lijn: storage for xth line of file,booly: true/false output. Settings:reset: 1/0,load: 1/0,startfile: filename
char file[15]="settings.txt",lijn[25],booly[10],reset,load,startfile[25];
int inp,i;
do {
i=1;
//Read file and output current settings to user
FILE * bestand;
bestand=fopen(file,"rt");
fgets(lijn,999,bestand);
while (!feof(bestand)) {
//i determines what line we're on -> There are always 3 lines
//1st line can be 0 or 1 -> Reset screen after cmd?
//2nd line can be 0 or 1 -> Load file
//3th line is a string (filename) -> .txt is automatically added when loading file
getBool(lijn,booly);
if (i==1) {
printf("%d - Reset screen after every command: %s\n",i,booly);
reset=lijn;
} else if (i==2) {
printf("%d - Load file on startup: %s\n",i,booly);
load=lijn;
} else if (i==3) {
strcpy(startfile,lijn);
}
fgets(lijn,999,bestand);
i++;
}
fclose(bestand);

printf("Pick a setting to change or enter 0 to cancel.\nChoose: ");
//Let user choose a value: 0, 1 or 2. Anything else won't
inp=inlezen("012");
printf("\n");

//Process users choice
if (inp=='1') {
//Toggle reset option, remain other options
bestand=fopen(file,"wt");
if (reset=='0') {
reset='1';
} else if(reset=='1') {
reset='0';
}
fprintf(bestand,"%s\n",reset);
fprintf(bestand,"%s\n",load);
fprintf(bestand,"%s\n",startfile);
fclose(bestand);
} else if (inp=='2') {
//Toggle load on startup option + read filename to start, remain reset option
bestand=fopen(file,"wt");
if (load=='0') {
load='1';
} else if(load=='1') {
load='0';
}
fprintf(bestand,"%c\n",reset);
fprintf(bestand,"%c\n",load);
if (load=='1') {
printf("\nWhich file must be loaded on startup?\nGive name: ");
scanf("%s",&startfile);
}
fprintf(bestand,"%s\n",startfile);
fclose(bestand);
}
} while (inp!='0');
printf("\n");
}

最佳答案

However, when I run the code below, my .exe crashes.

您定义了 char …reset,load,然后使用错误的转换说明符 s 将这些字符传递给 fprintf():

            fprintf(bestand,"%s\n",reset);
fprintf(bestand,"%s\n",load);

如果您的编译器没有警告这些变量的不一致使用,您应该使用更好的编译器;如果是这样,您应该注意警告。

关于c - 制作简单的设置文件时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41240521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com