My question is why won't this loop? It automatically goes to the end of the code without looping during input.
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
char input[1];
int x = rand() & 25;
int y = rand() & 25;
int a = x+y;
int answer;
cout<<"This program is a simple test. You must add 2 random numbers.\n\n";
do {
cout<<"The question is: " << x << "+" << y << "= ";
cin>>answer;
cout<<"\n\n";
if (answer == a){
cout<<"Correct!\n\n";
cout<<"Would you like to try a new problem? (y/n): ";
gets(input);
}
else if (answer != a) {
cout<<"Incorrect!\n\n";
cout<<"Would you like to try again? (y/n): ";
gets(input);
}
} while (strcmp (input, "y") == 0);
cout<<"Okay.";
cin.get();
}
You need to clear buffer using fflush(stdin). Try to use this version.
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
srand((unsigned)time(NULL));
char input[1];
int x = rand() % 25;
int y = rand() % 25;
int a = x+y;
int answer;
cout<<"This program is a simple test. You must add 2 random numbers.
";
do {
cout<<"The question is: " << x << "+" << y << "= ";
cin>>answer;
cout<<"
";
if (answer == a){
cout<<"Correct!
";
cout<<"Would you like to try a new problem? (y/n): ";
fflush(stdin);
gets(input);
}
else if (answer != a) {
cout<<"Incorrect!
";
cout<<"Would you like to try again? (y/n): ";
fflush(stdin);
gets(input);
}
} while (strcmp (input, "y") == 0);
cout<<"Okay.";
cin.get();
}