Writing a horse racing program that uses structures. I have no errors that i can
ID: 3641316 • Letter: W
Question
Writing a horse racing program that uses structures. I have no errors that i can find, but I am getting a floating exception (core dumped). I have tried different versions of the code and am still getting that error when i run it or a segmentation fault (core dumped. I believe the problem is in my infile/while loop but I have not been able to find out where. How do you fix this error?The input file looks like:
Buster
3 4 5 2
Sandy
1 2 3 2
Jelly Bean
3 3 3 3
main code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const int NAMESIZE = 10;
struct horsestats
{
char name[NAMESIZE];
int odds;
int firstqrt;
int secondqrt;
int thirdqrt;
int fourthqrt;
};
const int RACERS = 10;
horsestats horse[RACERS];
int main ()
{
ifstream input;
char infile[100];
int size = 0;
int position = 0;
int total = 0;
cout << "What is the input file? ";
cin.getline(infile, 100);
input.open(infile);
while(!input.eof())
{
horse[size].odds = 0;
input.getline(horse[size].name, NAMESIZE);
input >> horse[size].firstqrt;
horse[size].odds = horse[size].firstqrt;
input >> horse[size].secondqrt;
horse[size].odds += horse[size].secondqrt;
input >> horse[size].thirdqrt;
horse[size].odds += horse[size].thirdqrt;
input >> horse[size].fourthqrt;
horse[size].odds += horse[size].fourthqrt;
input >> ws;
size++;
}
input.close();
srand(time(0));
horsestats horsesup[4];
for(int i = 0; i < 4; i++)
horsesup[i] = horse[rand() % 10];
for(int i = 0; i < 4; i++)
total += horsesup[i].odds;
for(int i = 0; i < 4; i++)
horsesup[i].odds = total / horsesup[i].odds;
for(int i = 0; i < 4; i++)
{
cout << "Lake Side Horse Raceway" << endl << endl;
cout << "No" << "Horse" << "Odds";
cout << "q1" << "q2" << "q3";
cout << "q4" << endl;
cout << i + 1 << horsesup[i].name;
cout << horsesup[i].odds << "-to-1";
cout << horsesup[i].firstqrt;
cout << horsesup[i].secondqrt;
cout << horsesup[i].thirdqrt;
cout << horsesup[i].fourthqrt << endl;
i++;
}
return 0;
}
Explanation / Answer
Before you ever get to the while loop to read the input file, the file is opened and you continue without checking to see if the open worked... It is good practice to always include some error checking after opening the file, before continuing on like this: input.open(infile); if (!input.good()) { coutRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.