0
string code[4] = {"G", "O", "B", "R"};
string colorPegs[6] = {"R", "B", "Y", "G", "O", "B"};
string userGuess;

    getline(cin,userGuess);

Those are the important lines of code in my question.

The user will input 4 letters, for example "BBYG"

How can I make a for loop that checks the first char of user input with the first char of code, and sees if it matches?

for example:

string code is GOBR

user inputs BBBR. In user input, only one letter matches the code, which is the third B, how can I check for this with a for loop?

3
  • What are you trying to do? Do you want to check for a complete match? Or count the number of characters that match? Or find the index of the first match? Can you edit your question to provide more information? Commented Oct 9, 2013 at 21:53
  • To check if the first letter is in an Array you can use Array.contains. Docs: msdn.microsoft.com/en-us/library/bb384015(v=vs.100).ASPXchar firstletter = userGuess[0]; Commented Oct 9, 2013 at 21:58
  • All your "strings" in the first two lines consist of only a single character. Consider using real characters to simplify the task. Commented Oct 9, 2013 at 21:58

2 Answers 2

1

Try with this code assuming you want to find a match if they are at the same position :

for(int i = 0; i < code.length(); ++i)
{
    if(code[i] == user[i]) return true;    // Match found here.
}
return false;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

#include <algorithm>

int main()
{
    std::string code{"GOBR"};
    std::string input;

    std::cin >> input;

    auto match = [&] (char c)
    {
        return std::find(code.begin(), code.end(), c) != code.end();
    };

    if (std::any_of(input.begin(), input.end(), match))
    {
        // match
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.