gpt4 book ai didi

C - 在 .txt 中读/写 int 变量

转载 作者:行者123 更新时间:2023-11-30 21:10:19 25 4
gpt4 key购买 nike

我开始学习 C,目前正在编写一个基于文本的类似彩票的小游戏。但我需要一种方法来在游戏结束时存储该值,以便可以为下一次游戏保留它。我在下面编写了一个更简单的代码来代表我所需要的。请帮忙。

#include <stdio.h>

int main() {
//TODO get "int saved" from save.txt
printf("Value saved: %d\n", saved);
printf("Add: ");
int add;
scanf("%d", &add);
int new = saved+add;
printf("New value: %d\n", new);
//TODO save "int new" to save.txt
}

保存.txt:

100

最佳答案

试试这个

FILE *file;
int saved;
int add;

file = fopen("saved.txt", "r");
if (file == NULL)
{
fprintf(stderr, "error opening `saved.txt'\n");
return -1;
}

if (fscanf(file, "%d", &saved) != 1)
{
fprintf(stderr, "file `saved.txt' corrupted\n");
fclose(file);
return -1;
}

fprintf(stdout, "please input an integer > ");
if (scanf("%d", &add) != 1)
{
fprintf(stderr, "invalid input\n");
fclose(file);
return -1;
}
fclose(file);

file = fopen("saved.txt", "w");
if (file != NULL)
{
fprintf(file, "%d\n", saved + add);
fclose(file);
}

关于C - 在 .txt 中读/写 int 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019021/

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