gpt4 book ai didi

c++ - EXC_BAD_ACCESS 重新运行程序时

转载 作者:行者123 更新时间:2023-11-28 05:24:52 26 4
gpt4 key购买 nike

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

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

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

bloodInFile >> a[i];

#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;
}

最佳答案

在函数 getPints 中检查您是否超出数组 a 的范围,在此处添加检查

 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();
}

附言正如@JonathanLeffler 所说(我 100% 同意他的观点),当您不知道可能有多少输入时,最好使用动态数组(例如 vector)来解决此类问题。

关于c++ - EXC_BAD_ACCESS 重新运行程序时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756097/

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