0

Is it okay or valid to use this? string answer = "A || B"; than using this if (answer == A || answer == B)?Because in my program I want to use that condition inside a while if statements. I want to put that two option condition in my while statement but it gets 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! ";
}
Eenalpe1
  • 47
  • 4

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
  • 69,090
  • 10
  • 44
  • 65