lundi 2 novembre 2015

C++ 'else' in loops

In C++, I have run into a problem when I am doing loops. I just know there is an obvious solution I am just overlooking in my work. Here is an example for reference- `

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

string loop();

int main()
{
    string answer;
    do
    {
        cout << "Do you wish to be asked this question again?: ";
        cin >> answer;
        if (answer == "no" || answer == "No" || answer == "NO")
            cout << "As you wish";
        else if (answer == "yes" || answer == "Yes" || answer == "YES")
            cout << "";
        else
        {
            cout << "You didn't answer yes or no\n";
            loop();
        }
    }while (answer == "yes" || answer == "Yes" || answer == "YES");
    return 0;
}

string loop()
{
        string answer;
        cout << "Do you wish to be asked this question again?: ";
        cin >> answer;
        if (answer == "no" || answer == "No" || answer == "NO")
            cout << "As you wish";
        else if (answer == "yes" || answer == "Yes" || answer == "YES")
            cout << "";
        else
        {
            cout << "You didn't answer yes or no\n";
            loop();
        }
        return answer;
}`

When I am doing an If-else in a loop, I run into a problem when it comes to the 'else' section. I cant seem to figure out how to display something that tells the user there is an error, and then re-run the same sequence. For example, in the program I included, when the user enters something other than yes or no, I am not sure how to show an error statement and then loop it back to the top so it asks the question again.

Aucun commentaire:

Enregistrer un commentaire