重新运行程序时EXC_BAD_ACCESS

时间:2016-11-23 04:35:07

标签: c++

所以这是我在班上为CS实验室写的一个程序。它被修改,以便从文本文件输入并输出到另一个文本文件。在进行计算之后,它会询问用户是否要重新运行程序,这只是main中的while循环。为什么程序重新运行时会出现此错误?

线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x7ffeb1d82bc8)

它出现在getPints函数的这一行:

bloodInFile>> A [1];

#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
#include <fstream>

using namespace std;

const int MAX_HOURS = 7;

void getPints(double a[], int h);
double getAverage(double a[], int h);
double getHigh(double a[], int h);
double getLow(double a[], int h);
void displayInfo(double a, double b, double c);

int main()
{
    string again = "yes";
    double pints[MAX_HOURS];
    double getHigh(double pints[], int MAX_HOURS);

    while (again == "yes")
    {
        getPints(pints, MAX_HOURS);
        getHigh(pints, MAX_HOURS);
        displayInfo(getAverage(pints, MAX_HOURS), getHigh(pints, MAX_HOURS), getLow(pints, MAX_HOURS));

        cout << "Do you want to run again (yes or no)? ";
        cin >> again;
    }

    return 0;
}

void getPints(double a[], int h)
{
    int i;
    ifstream bloodInFile;

    bloodInFile.open("bloodDrive.txt");

    if (!bloodInFile)
        cout << "Cannot open file." << endl;

    while (!bloodInFile.eof())
    {
        bloodInFile >> a[i];
        i++;
    }

    bloodInFile.close();
}

double getAverage(double a[], int h)
{
    int i;
    double totalPints = 0;
    double averagePints;

    for (i = 0; i <= h - 1; i++)
        totalPints = totalPints + a[i];
    averagePints = totalPints / i;

    return averagePints;
}

double getHigh(double a[], int h)
{
    int i;
    double highest = a[0];

    for (i = 1; i < h; i++)
    {
        if (a[i] > highest)
            highest = a[i];
    }

    return highest;
}

double getLow(double a[], int h)
{
    int i;
    double lowest = a[0];

    for (i = 1; i < h; i++)
    {
        if (a[i] < lowest)
            lowest = a[i];
    }

    return lowest;
}
void displayInfo(double a, double b, double c)
{
    ofstream bloodOutFile;

    bloodOutFile.open("bloodResults.txt");

    bloodOutFile << "Average pints: " << setprecision(1) << showpoint<< fixed << a << endl;
    bloodOutFile << "Highest pints: " << setprecision(1) << showpoint<< fixed << b << endl;
    bloodOutFile << "Lowest pints: " << setprecision(1) << showpoint<< fixed << c << endl;
}

1 个答案:

答案 0 :(得分:1)

检查您是否不在函数a中的数组getPints范围内添加检查

 while (!bloodInFile.eof())
 {
   if(i >= h)
       break;
   bloodInFile >> a[i];
   i++;
 }

因为如果你在bloodDrive.txt文件中有更多行MAX_HOURS。另外,我没有看到你在某个地方初始化i,我认为它应该等于0(i=0),所以你的功能看起来应该是那样

void getPints(double a[], int h)
{
    int i = 0;
    ifstream bloodInFile;

    bloodInFile.open("bloodDrive.txt");

    if (!bloodInFile)
        cout << "Cannot open file." << endl;

    while (!bloodInFile.eof())
    {
        if(i > h)
            break;
        bloodInFile >> a[i];
        i++;
    }

    bloodInFile.close();
}

P.S。正如@JonathanLeffler所说(我同意他100%)当你不知道输入多少时,最好使用动态数组(vector例如)来解决这个问题。