从文件读取时崩溃

crash when reading from a file

本文关键字:崩溃 读取 文件      更新时间:2023-10-16

首先,我想让你知道我是一名大学生(我们的编程教学大纲还没有那么先进)(顺便说一句,我不问我的作业答案等,我只是在练习)。

好的,所以我有 2 个问题

  1. 我的代码中的某些函数更改了数组的值(当我不希望它时)
  2. 我真的不知道,但似乎从文件中获取一些值以存储到我的数组中会使程序崩溃,此外,在摆弄了一下代码(我不知道发生了什么变化)之后,它在所述部分不再崩溃,但它仍然在代码执行结束时崩溃。

我希望你们能帮助我,我已经找了一整天了。

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void readFile (float x[], int &y) {
    ifstream load;
    string filename;
    cout << "Enter the name of the file: ";
    cin >> filename;
    load.open(filename.c_str());
    while (!load.eof()) {
        load >> x[y];
        y++;
    }
    if (!load) {
        cout << "asd";
    }
}
void computeC (float x[], int y, float z[]) {
    int v=0;
    for (v=0; v<=y; v++) {
        z[v] = (5 * (x[v] - 32)/9);
    }
}
float average (float x[], int y) {
    int v=0;
    float sum=0;
    for (v=0; v<=y; v++) {
        sum += x[v];
    }
    return sum / v;
}
void grade (float x[], char grades[], int y, int &hi, int &med, int &lo) {
    int v=0;
    hi = med = lo = 0;
    for (v=0; v<=y; v++) {
        if ( x[v] >= 35) {
        grades[v] = 'H';
        hi++;
        }
        else if ( (x[v] < 35) && (x[v] >= 20) ) {
        grades[v] = 'M';
        med++;
        }
        else if ( x[v] < 20 ) {
        grades[v] = 'L';    
        lo++;
        }
    }
}
void writeFile (float x[], float y[], int z, char w[]) {
    ofstream save;
    int v=0;

    for (v=0; v <= z; v++) {
        cout << "C(Celcius)" << left << setw(5);
        cout << "F(Farenheit)" << left << setw(5);
        cout << "Descriptionn";
        cout << right << setw(7) << y[v];
        cout << left << setw(8) << x[v];
        cout << left << setw(8) << w[v];        
    }
}
int main(int argc, char** argv) {
    int ctr=0, high, medium, low;
    float F[ctr], C[ctr], ave;
    char grades[ctr];

    readFile (F, ctr);
    computeC (F, ctr, C);
    ave = average (C, ctr);
    grade (C, grades, ctr, high, medium, low);
    cout << "Average of the temperatures: " << ave << endl;
    cout << "Number of high temperatures: " << high << endl;
    cout << "Number of medium temperatures: " << medium << endl;
    cout << "Number of low temperatures: " << low << endl;
    //writeFile (F, C, ctr, grades);

    return 0;
}

(来自 https://drive.google.com/file/d/0BxeZTCUL3Q4oZHlqWFdjMDZub0E/view?usp=sharing 的代码)

无需检查整个代码,我可以直接想到代码的某些部分。

让我从

while (!load.eof()) {
        load >> x[y];
        y++;
    }

写入的值超过 x[] 可以容纳的值,在这种情况下,程序将崩溃。

确保只写入阵列,最多不超过最大分配的内存。

问题是 !load.eof() 不会做你期望它做的事情,因为它将从文件末尾之外读取。它会再次执行你的循环太多。

第二:

 int ctr=0, high, medium, low;
    float F[ctr], C[ctr], ave;
    char grades[ctr];

ctr 0,因此您声明了包含 0 个元素的 F, c and grades 数组。这不是很聪明;)您无法从中读取或写入。