用c语言实现mokit 题目描述 从键盘输入一行用空格分隔的整数,写入in.txt文件,写入完成后,再从in.txt文件中把数据读取出来,进行相加后,把把它们的和保存out.txt文件中,最后把out.txt内存储的结果读取输出到屏幕显示出来。
时间: 2023-05-23 08:01:06 浏览: 252
以下是用C语言实现mokit的代码:
#include <stdio.h>
int main() {
// 读取输入的整数并写入in.txt文件
FILE *fp1;
fp1 = fopen("in.txt", "w");
if (fp1 == NULL) {
printf("Error creating in.txt file\n");
return -1;
}
printf("Please input a list of integers separated by spaces:\n");
int num, sum=0;
while (scanf("%d", &num) == 1) {
fprintf(fp1, "%d ", num);
}
fclose(fp1);
// 从in.txt文件中读取整数并相加
FILE *fp2;
fp2 = fopen("in.txt", "r");
if (fp2 == NULL) {
printf("Error reading in.txt file\n");
return -1;
}
printf("\nCalculating sum of integers:\n");
int current_num;
while (fscanf(fp2, "%d", ¤t_num) == 1) {
sum += current_num;
}
fclose(fp2);
// 把相加后的和保存到out.txt文件中
FILE *fp3;
fp3 = fopen("out.txt", "w");
if (fp3 == NULL) {
printf("Error creating out.txt file\n");
return -1;
}
fprintf(fp3, "%d", sum);
fclose(fp3);
// 从out.txt文件中读取结果并输出到屏幕
FILE *fp4;
fp4 = fopen("out.txt", "r");
if (fp4 == NULL) {
printf("Error reading out.txt file\n");
return -1;
}
printf("\nSum of integers: ");
int result;
fscanf(fp4, "%d", &result);
printf("%d", result);
fclose(fp4);
return 0;
}
请注意,这是一份可以实现该功能的基本代码,但是可能并不是最完美的解决方案。在实际使用时,需要考虑更多的异常情况和代码优化。
阅读全文