Okay, let's do this then. :-)
First off, I'm going to change the string to a char, since we're only interested in one letter.
There are a couple of issues with your or condition. The compiler sees the second as a string literal (a const char* containing the letter b), which will always evaluate to true in an if statement. We need to explicitly state the condition.
|
if (letter != "a" || letter != "b")
|
Have a bit of a think about that statement, though. If the letter isn't 'a' OR if the letter isn't 'b'. Well, if the the letter is 'a', then it isn't 'b' and vice versa. In short, this if statement is always going to evaluate to true. What we want is:
|
if (letter != 'a' && letter != 'b')
|
You're right about the loop, so let's get one in there.
1 2 3 4 5
|
while (letter != 'a' && letter != 'b')
{
std::cout << "Incorrect letter, enter a or b:";
std::cin >> letter;
}
|
What you'll often notice with these sorts of input loops is that it can go a bit crazy if someone enters the wrong input and could do things like spit out the cout statements in the loop multiple times. For this reason, it's a good reason to tell std::cin to ignore whatever is remaining in the buffer.
1 2 3 4 5 6
|
while (letter != 'a' && letter != 'b')
{
std::cout << "Incorrect letter, enter a or b:";
std::cin.ignore(256, '\n');
std::cin >> letter;
}
|
The arguments here basically tell it to to extract and ignore 256 characters or up until it finds a newline.
Another thing we can do is check that the input to the std::cin stream is as expected. Explaining this one might be a bit overkill right now, but you can do it by adding this to your loop conditions.
1 2 3 4 5
|
while ( !(std::cin >> letter) || (letter != 'a' && letter != 'b'))
{
std::cout << "Incorrect letter, enter a or b:";
std::cin.ignore(256, '\n');
}
|
Note how we no longer need to get our input in the loop; we're actually doing it in the condition.
Finally, we need to cater for uppercase characters. A and B are legitimate entries, so we need to allow them. We could add two more conditions in our loop but there's an easier way. C++ providers a tolower function, which is available from the cctype header (
http://www.cplusplus.com/reference/cctype/tolower/). We can make use of that to allow uppercase characters. This makes our final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <cctype>
int main(int argc, const char* argv[])
{
char letter;
std::cout << "Enter a or b:";
while ( !(std::cin >> letter ) ||
(std::tolower(letter) != 'a' && std::tolower(letter) != 'b'))
{
std::cout << "Incorrect letter, please enter a or b:";
std::cin.ignore(256, '\n');
}
std::cout << "Congratulations, you entered " << letter << std::endl;
return 0;
}
|
Hope this helps. :-)
Edit: Yikes, I started writing this, went to get something to eat and then continued afterwards. I didn't realise someone had replied in that time. :-)