The bug starts at cin.getline ( string, 25, '\n' ); or the line below it (strtod). If I use cin, it works, except I cannot quit out. If I type anything that's not a double, an infinite loop runs. Need help. Basically, the first iteration runs, does not ask for input, so the user gets the math questions wrong. The second iteration works fine. And the next is fine, too. If I back out, using q, I get dumped back to the mode-chooser. After choosing a mode, the bug reappears for the first iteration. Next iterations it's gone.
int main()
{
char choice, name[25], string[25], op;
int operator_number, average, difference, first_operand, second_operand, input, answer, total_questions = 0, total_correct = 0;
double dfirst_operand, dsecond_operand, dinput, danswer, percentage;
bool rounding = false;
srand ( time(NULL) );
cout << "What's your name?\n";
cin.getline ( name, 25, '\n' );
cout << '\n' << "Hi, " << name << ".";
do {
do {
cout << "\nWhich math operations do you want to practice?\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n 5. Mixed\n 6. Difference of squares multiplication.\nChoose a number (q to quit).\n";
cin >> choice;
} while( choice < '1' || choice > '6' && choice!= 'q');
cout << "\n";
switch(choice) {
case '1':
while( string[0]!= 'q') {
dfirst_operand = rand() % 15 + 1;
dsecond_operand = rand() % 15 + 1;
danswer = dfirst_operand + dsecond_operand;
cout << dfirst_operand << " + " << dsecond_operand << " equals?\nEnter q to quit.\n";
cin.getline ( string, 25, '\n' );
dinput = strtod( string,NULL);
//cin >> dinput;
if(string[0]!='q') {
++total_questions;
if(dinput==danswer) {
++total_correct;
cout << "Correct. " << total_correct << " correct out of " << total_questions << ".";
} else {
cout << "Wrong. " << dfirst_operand << " + " << dsecond_operand << " equals " << danswer << ".\n" << total_correct << " correct out of " << total_questions << ".";
};
percentage = floor(10000 * (float) total_correct / total_questions)/100;
cout << ' ' << percentage << "%.\n\n";
}
}
break;
}
} while(choice!='q');
return 0;
}