[URGENT]WHAT IS WRONG WITH MY CODE? DON\'T CHANGE ANY OF THE FORMAT. When I run
ID: 3774554 • Letter: #
Question
[URGENT]WHAT IS WRONG WITH MY CODE? DON'T CHANGE ANY OF THE FORMAT.
When I run this, it gets crashed. Problem should be in Question.cpp. Maybe sentence, but I dont know.
UPDATE:
for(i = 0; 0 < num; i++) <-------- THIS WAS THE MY MISTAKE.
main
#include
#include
#include
#include
#include "Question.h"
using namespace std;
int main()
{
ifstream file;
int num, score1, score2, i, j;
string a, player1, player2;
file.open("TriviaQuestions.txt");
if(!file)
{
cout << "Failed to open the file.";
exit(EXIT_FAILURE);
}
file >> num;
Question game(num);
for(i = 0; 0 < num; i++)
{
getline(file, a, ' ');
game.sentence(i, a);
for (j = 1; j < 5; j++)
{
getline(file, a, ' ');
game.answer(j, a);
}
game.rad();
}
file.close();
cout << "Enter a name for first player. ";
getline(cin, player1);
score1 = 0;
cout << "Enter a name for second player. ";
getline(cin, player2);
score2 = 0;
return 0;
}
Question.cpp
#include
#include
#include
#include
#include "Question.h"
using namespace std;
Question:: Question(int size)
{
cor = 1;
list = new std::string *[size];
for (int i = 0; i < size; i++)
{
list[i] = new std::string[5];
}
}
Question:: ~Question()
{
delete [] list;
}
void Question:: sentence(int i, std::string a)
{
ptr = list[i];
ptr[0] = a;
}
void Question:: answer(int index, std::string a)
{
ptr[index] = a;
}
int Question:: rad()
{
int ind;
srand((int)time(0));
for(int z = 4; z < 13; z++)
{
ind = (rand() % 4) + 1;
temp = ptr[ind];
ptr[ind] = ptr[(z % 4) + 1];
ptr[(z % 4) + 1] = temp;
if(ind == cor)
cor = (z % 4) + 1;
}
return 0;
}
Question.h
#ifndef QUESTION_H_INCLUDED
#define QUESTION_H_INCLUDED
class Question
{
private:
int cor;
std::string *ptr;
std::string **list;
std::string question;
std::string temp;
public:
Question(int size);
~Question();
void sentence(int i, std::string a);
void answer(int index, std::string a);
int rad();
};
#endif // QUESTION_H_INCLUDED
Explanation / Answer
For all values of num greater than 0 makes the loop for(i = 0; 0 < num; i++) an infinite loop which will keep on go until program runs out of memory and crashes.
Always remember to check the terminating condition.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.