Answer to Question #24517 in C++ for Michael Young

Question #24517
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();
}
1
Expert's answer
2013-02-19T08:30:47-0500
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();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS