I want the program to return the user to the begining of the question and have them enter a new answer. Only problem is it repeatedly loops the lines:
cout << "The answer you've selected does not exsist! Please try again." << endl;
QuestionA();
which as you can imagine just leaves a wall of ""The answer you've selected does not exsist! Please try again." in the window. Any ideas on how to fix it?
#include <iostream>
usingnamespace std;
int a;
void QuestionA()
{
cout << "Is it freaking you out?" << endl;
cout << "1. Yes it is!\n2. Not at all." << endl;
cin >> a;
if (a == 1) {
cout << "valid answer 1" << endl;
}
elseif (a == 2) {
cout << "valid answer 2" << endl;
}
else {
cout << "The answer you've selected does not exsist! Please try again." << endl;
QuestionA();
}
}
int main()
{
a = 0;
cout << "Are you about to squish that bug?\nBefore you do, ask yourself the following:\n(For each question please choose the answer that best fits)\n" << endl;
QuestionA();
return 0;
}
#include <iostream>
usingnamespace std;
void QuestionA(string a)
{
cout << "Is it freaking you out?" << endl;
cout << "1. Yes it is!\n2. Not at all." << endl;
cin >> a;
if (a == "1") { //Now "a" is a string, so I have to put the numbers as part of a string, not a number
cout << "valid answer 1" << endl;
}
elseif (a == "2") {
cout << "valid answer 2" << endl;
}
else {
cout << "The answer you've selected does not exsist! Please try again." << endl;
QuestionA(a);
}
}
int main()
{
string a =""; //Initializing the string.
cout << "Are you about to squish that bug?\nBefore you do, ask yourself the following:\n(For each question please choose the answer that best fits)\n"<<endl;
QuestionA(a);
return 0;
}
The code you posted works for me if I enter an invalid number, but not if I enter a letter. The reason is that line 12 fails and leaves the letter in the input buffer.
Another problem is that you shouldn't use recursion when you really just want a loop. Here's a fixed version:
#include <iostream>
#include <limits>
usingnamespace std;
int a;
void QuestionA()
{
while (true) {
cout << "Is it freaking you out?" << endl;
cout << "1. Yes it is!\n2. Not at all." << endl;
cin >> a;
if (a == 1) {
cout << "valid answer 1" << endl;
break;
}
elseif (a == 2) {
cout << "valid answer 2" << endl;
break;
}
else {
cout << "The answer you've selected does not exsist! Please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
}
int main()
{
a = 0;
cout << "Are you about to squish that bug?\nBefore you do, ask yourself the following:\n(For each question please choose the answer that best fits)\n" << endl;
QuestionA();
return 0;
}