# Validating Yes/No answers in C++

I intend to accept all of the following answers:

• y
• Y
• yes
• YES
• Yes
• plus mixtures, such as yeS, yES, which I didn't intend to accept but it's a consequence of my code
• the same applies to No and its variants

#include <iostream>     // std::cout, std::cin
#include <string>       // std::string
#include <algorithm>    // std::transform

int main()
{

do
{
std::cout << "Should the password include digits? [Y/n] ";

return 0;

}


It works flawlessly, or it seems so. Is there better approach?

• I would simply defer it to regex library in a case like this. It is simple to improve and extend. Also, it is safer if your reviewer/manager knows regex. He can validate it since it is somewhat standardized. – Etherealone Nov 23 '17 at 19:19

You have a common bug that will send you into an infinite loop. :-)

When reading data (especially user input data) you must validate the read worked correctly. If the read fails and sets one of the error flags on the stream than any subsequent attempt to read will silently be ignored.

Thus usually read operations are checked in the loop test.

std::string word;
while(word != "STOP") {
std::cin >> word;
std::cout << "Word: " << word << "\n";
}


In the above you will enter an infinite loop if your hit an EOF marker (Note: this can be generated from the keyboard) or in unix systems a file can be piped to the input stream of an application etc..

To prevent this you test the result of the read operation.

std::string word;
while(std::cin >> word && word != "STOP") {
std::cout << "Word: " << word << "\n";
}


This works because of two things. The operator>> returns a reference to the stream (usually for chaining). When a stream is used in a boolean context (like a test) it is converted to a bool using operator bool which calls good() which returns true if the stream is still in a good state (ie the read operation did not cause an error).

Secondly declares variables as close to the use point as possible.

This is a good habit to get into with C++ as objects have constructors that can potentially be expensive (also destructors). Declaring them at the top of the function and then not using them is wasteful.

Also be declaring them near the use point also allows for locality of reading when checking variables types.

    std::string answer;


This is declared at the top but only used inside the loop.

Also prefer not to use return 0; in main() when the application never returns an error state. The compiler will automatically generate the required return 0 and leaving it off is a marker used by programs to indicate that the program never fails.

Give this I would rewrite as:

bool checkAnswerOK(std::string& answer, bool& result)
{
[](unsigned char x){return ::tolower(x);});

}

bool question_yesno(std::string const& message)
{
bool        result;

std::cout << message << "? [Y/n]\n";
{
<< message << "? [Y/n]\n";
}
if (!std::cin) {
// We never got an answer.
// Not much we can do here. Probably give up?
}
return result;
}

int main()
{
}

• will silently be ignored very nice API design... – usr Nov 20 '17 at 21:42
• @usr By design. So when you get to a place that you want to check things you can validate if it worked or not. You can of course change that behavior to much more noisy (throw an exception on error) but when dealing with user input this is less desirable behavior. – Martin York Nov 20 '17 at 22:02
• Usually you need to consume the result of a read immediately. Therefore you need to check immediately for errors. This question is an example of that. Exceptions would be suited very nicely for this. Altering instance state and needing to query the object to find out about errors seems like an unnecessary complication. We are not talking about invalid input. We are talking about a failed IO operation. – usr Nov 21 '17 at 13:27
• @usr Which is why we don't use Exceptions (Exceptions is a terrible mechanism for handling user error). Exceptions are designed for situations where you don't expect an error and you are passing that error up to a higher context to be handled by an unknown system manager. User errors (are expected) and thus handled at the point where they are generated and thus much better handled by error codes. – Martin York Nov 21 '17 at 18:51
• @usr I point you at Sutters Mill to go read about the topic. I am sure he has plenty of articles to cover the subject more thoroughly than we can do in comments. – Martin York Nov 21 '17 at 18:54

For a beginner, that's very good code.

There is one thing that almost all C++ programmers get wrong, and that's calling ::tolower with a char argument. This leads to undefined behavior as soon as you enter German umlauts or café. Your program may appear to work, but it is not guaranteed to do so. Any good tutorial on the tolower function (which requires #include <ctype.h>, by the way) should mention that its argument must be cast to unsigned char.

For now, let the code as it is, but keep that in mind when you write code that has to accept untrusted data.

The next useful step would be to extract this code into its own function. Imagine how easy your code would look like if you could already call yesno with a prompt:

bool include_digits = yesno("Should the password include digits?");


To make this code work, you have to define the function like this:

bool yesno(const std::string &prompt) {
}

• I must have been in a good mood when I wrote the above text. Now that I look at the code again, I see that I was just impressed that the code was not using namespace std. The code still leaves much room to improve. See codereview.stackexchange.com/q/180907 for an improved version of the code. – Roland Illig Nov 20 '17 at 21:34

The existing reviews cover the most important aspects, I think, but as a supplement, I thought I'd show how it might be done with std::regex_match

#include <string>
#include <regex>
#include <iostream>

/* return 'y' if the answer matches the first regex,
*        'n' if the answer matches the second regex,
*        '\0' if the answer matches neither
*/
char yesno(const std::string &answer, const std::regex &yes, const std::regex &no) {
return 'y';
} else if (std::regex_match(answer, no)) {
return 'n';
}
return '\0';
}

int main() {
#if ENGLISH
static const std::regex yes{"y|yes", std::regex::icase | std::regex::optimize};
static const std::regex no{"n|no", std::regex::icase | std::regex::optimize};
static const std::string prompt{"Should the password include digits? [y/n] "};
#else
static const std::regex yes{"j|ja", std::regex::icase | std::regex::optimize};
static const std::regex no{"n|nein", std::regex::icase | std::regex::optimize};
static const std::string prompt{"Soll das Passwort Ziffern enthalten? [j/n] "};
#endif
std::string response;
std::cout << prompt;
std::cin >> response;
if (std::cin) {
}
}
}


As you can see, the regex is not so hard to use and offers a great deal of flexibility. In this case, I've showed how one could support English or German versions as an example.

• I would rather pull the strings from L10N library than hard code them. – Martin York Nov 21 '17 at 0:26
• @LokiAstari Sure, me too in real code, but that would have obscured the point I was trying to illustrate and the OP is a self-described beginner. – Edward Nov 21 '17 at 0:37

Lots of "fancy" solutions, but I haven't seen anyone mention the simplest one: Just check whether the first character is y or n

std::cout << "Should the password include digits? [Y/n] ";


You can still convert to upper of lower to simplify even more...

Based on the "php" answer by @WesToleman below, you could use:

std::cout << "Should the password include digits? [Y/n] ";
{
case 'y':
case 'Y':
case 'n':
case 'N': return true;
}
return false;


You could add default: return false; but I prefer this way. Pros: only evaluate answer[0] once.

• Unfortunately this returns true on inputs such as Yowsers! – Wes Toleman Nov 21 '17 at 1:39
• Yes it does - which is kind of in keeping with the original question plus mixtures, such as yeS, yES, which I didn't intend to accept but it's a consequence of my code - As I said it's the simple approach. – John3136 Nov 21 '17 at 1:40
• This is the first thing I thought of, and I'm sure i've used various "proper" utilities that work this way. You're asking the user to supply [y/n] in the question, and so it shouldn't come as a surprise that entering a string starting with y gets accepted as such. In my opinion trying to match a complete set of specific strings is a bit over-engineered for this. – USD Matt Nov 21 '17 at 12:53

Assuming you have a fairly recent c++ compiler (c++11 or later), you can do this with a bit less code. It also gives you more versatility over then answers you can accept:

#include <iostream>
#include <string>
#include <set>

int main()
{

std::set<std::string> validAnswers = {"Y", "y", "yes", "N", "n", "no", "si", "oui"};

do
{
std::cout << "Should the password include digits? [Y/n] ";

return 0;

}


If you want to get really fancy, you can even use this to sort out what you do next:

#include <iostream>     // std::cout, std::cin
#include <string>       // std::string
#include <set>

int main()
{

std::set<std::string> yesAnswers = {"Y", "y", "yes", "si", "oui"};
std::set<std::string> noAnswers = {"N", "n", "no"};

do
{
std::cout << "Should the password include digits? [Y/n] ";

std::cout << "do yes stuff" << std::endl;
std::cout << "do no stuff" << std::endl;
else
std::cout << "do anything that's left" << std::endl;

return 0;

}


My apologies, the C++ switch case only works on primitive types. That will teach me for writing answers late at night on my phone.

This alternative approach is O(1) however it is overkill for a small set of words such as in your question because the constant is larger than the time taken to run a small if or statement.

bool validWord(const std::string& word)
{
const static std::unordered_set<std::string> validWords({ "yes", "no", "y", "n" });
return validWords.count(word) == 1;
}