【数据结构】预备练习——文件读写

一、先看题目

使用一个文本文件存储一组数据(x),编程读取数据并计算y=1/(200-x)的值,显示并保存结果,如果是非法操作,输出"Error"。

具体要求:

1 输入数据要典型,有代表性,输入数据类型为float。

2 能够处理错误输入数据,并输出"Error"。

3 使用文本文件作为程序的输入和输出。

文件读写参考:

打开文件
fp=fopen("input.txt","r");

错误判断

cpp 复制代码
if(fp==NULL){
	printf("Not SUCH A FILE:%s",af);
	getch();
	return;
}

读入数据

cpp 复制代码
fscanf(fp,"%d",&num);
fscanf(fp,"%f,%d",&x[i],&y[i]);

打开文件(写文件)
fp=fopen("result.txt","w");

写数据
fprintf(fp,"%d,%.2f,%d,%.2f\n",i,x[i],y[i],b[i]);

下面是程序

cpp 复制代码
#include <iostream>
#include <cstdio>

int writeToFile(int n, FILE *f);
float fx(float x);

int main() {
    const int N = 100;

    // 打开文件并写入数据
    FILE *f = fopen("./input.txt", "w");
    if (f == NULL) {
        std::cerr << "Failed to open input file for writing!" << std::endl;
        return 1;
    }
    
    if (writeToFile(N, f) != 0) {
        std::cerr << "Error writing to file!" << std::endl;
        return 1;
    }

    // 打开文件并读取数据
    FILE *fin = fopen("./input.txt", "r");
    if (fin == NULL) {
        std::cerr << "Failed to open input file for reading!" << std::endl;
        return 1;
    }

    FILE *fout = fopen("./output.txt", "w");
    if (fout == NULL) {
        std::cerr << "Failed to open output file!" << std::endl;
        fclose(fin);
        return 1;
    }

    // 动态分配数组
    float *x = new float[N];
    float *y = new float[N];

    // 读取文件内容并计算
    for (int i = 0; i < N; i++) {
        fscanf(fin, "%f", &x[i]);
        y[i] = fx(x[i]);
    }

    // 将结果写入输出文件
    for (int i = 0; i < N; i++) {
        fprintf(fout, "%f\t%f\n", x[i], y[i]);
    }

    // 关闭文件并释放内存
    fclose(fin);
    fclose(fout);
    delete[] x;
    delete[] y;

    return 0;
}

// 向文件中写数据
int writeToFile(int n, FILE *f) {
    if (f == NULL) {
        std::cerr << "Not SUCH A FILE !" << std::endl;
        return 1;
    }
    for (float x = 0; x < n; x++) { 
        fprintf(f, "%f\n", x);
    }
    fclose(f);
    return 0;
}

// 定义函数 f(x)
float fx(float x) {
    if (x == 200) {
        fprintf(stderr, "Error: division by zero\n");
        return -1;
    } else {
        return 1 / (200 - x);
    }
}
相关推荐
星火开发设计5 分钟前
C++ 数组:一维数组的定义、遍历与常见操作
java·开发语言·数据结构·c++·学习·数组·知识
月挽清风27 分钟前
代码随想录第七天:
数据结构·c++·算法
小O的算法实验室29 分钟前
2026年AEI SCI1区TOP,基于改进 IRRT*-D* 算法的森林火灾救援场景下直升机轨迹规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
小郭团队1 小时前
2_1_七段式SVPWM (经典算法)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·硬件架构·arm·dsp开发
充值修改昵称1 小时前
数据结构基础:从二叉树到多叉树数据结构进阶
数据结构·python·算法
Deepoch2 小时前
Deepoc数学大模型:发动机行业的算法引擎
人工智能·算法·机器人·发动机·deepoc·发动机行业
-To be number.wan2 小时前
【数据结构真题解析】哈希表中等难度挑战:冲突处理与查找效率深度剖析
数据结构·哈希算法
csdn_aspnet2 小时前
C 语言的优雅回归:从零手造数据结构
c语言·数据结构
点云SLAM2 小时前
C++内存泄漏检测之Windows 专用工具(CRT Debug、Dr.Memory)和Linux 专业工具(ASan 、heaptrack)
linux·c++·windows·asan·dr.memory·c++内存泄漏检测·c++内存管理