0

Is it okay to use this string answer = "A || B";? than using this if (answer == A || answer == B)?.

I want to put two condition in the while statement in the program but I'm having a hard time solving it since it get's an error.

    // variables
    string answerA = "Coin";
    string guess;
    int guessCount = 0;
    int guessLimit = 3; 
    bool outOfGuesses = false;

    cout << "Question A!\n" << endl;
    cout << "A. What has a head and a tail, but no body?\n";

        // if the answer is not correct, ask again only 3 times
    while (answerA != guess && !outOfGuesses) {
        if (guessCount < guessLimit) {
            cout << "Answer: ";
            cin >> guess;
            guessCount++;
        } else {
            outOfGuesses = true;
        }
    }

    if (outOfGuesses)
    {
        cout << "Your answers are all wrong! Better luck next time :)";
    }
    else
    {
        cout << "Your answer is Correct! ";
    }
  • 1
    Using `string answer = "A || B";` is valid, but it doesn't mean to have 2 options unless you parse the string later to extract the 2 options. – MikeCAT May 19 '21 at 14:32
  • related/dupe: https://stackoverflow.com/questions/8781447/can-you-use-2-or-more-or-conditions-in-an-if-statement – NathanOliver May 19 '21 at 14:34
  • @MikeCAT how to parse and extract, sir? –  May 19 '21 at 14:34
  • @NathanOliver Is it possible to put it in a while if statement? –  May 19 '21 at 14:37
  • Did you read the link? – NathanOliver May 19 '21 at 14:37
  • @NathanOliver Yes, Sir. but my problem is I want to put it in my While if statements. I tried it several times but it only causes error. –  May 19 '21 at 14:42
  • 1
    Does this answer your question? [Can you use 2 or more OR conditions in an if statement?](https://stackoverflow.com/questions/8781447/can-you-use-2-or-more-or-conditions-in-an-if-statement) – Aldasa May 20 '21 at 12:02

1 Answers1

1

One std::string can hold only one string. You can use std::unordered_set to hold a set of multiple strings.

#include <iostream>
#include <string>
#include <unordered_set>

int main(void) {
    std::unordered_set<std::string> accept_list = {"A", "B"};
    std::string answer = "A";

    if (accept_list.find(answer) != accept_list.end()) {
        std::cout << "accept\n";
    } else {
        std::cout << "reject\n";
    }
    return 0;
}

(std::unordered_set is available since C++11. If your compiler doesn't support that, try std::set instead. Also initializer lists like accept_list = {"A", "B"} is since C++11, you may have to add each candidates separately in that case)

MikeCAT
  • 73,922
  • 11
  • 45
  • 70