I think you really need to consider this question.
No, this doesn't cover the case where the default response is supposed
to be N or space. The point of the function is to set a bit according
to query at the user prompt with the expectation that user will hit
return to indicate the default answer. The program it's derived from
asks a series of yes/no questions, some default to yes, some default
to no. A response other than empty string or Y or N returns false.
Only a Y answer can set it true in the case of a default no
expectation and any other input results in the default case.
Yes, I understood your intent. Unfortunately I've run out of
explanations so I simply offer you a test program that provides fake
input to both functions and shows the results:
#include <iostream>
#include <iomanip>
#include <algorithm>
const char *answer;
void getline(std::istream &is, std::string &line)
{
line = answer;
}
bool GetYesNo (std::string yn)
{
std::string str;
getline(std::cin, str);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::transform( yn.begin(), yn.end(), yn.begin(), ::tolower);
// if expecting y and get blank or y, return true
if ((yn.compare(0, 1, "y") == 0 && str.compare(0, 1, "") == 0) ||
str.compare(0, 1, "y") == 0)
return true;
// if expecting n and get n or blank, return false
if ((yn.compare(0, 1, "n") == 0 && str.compare(0, 1, "") == 0) ||
str.compare(0, 1, "n") == 0)
return false;
else
return false;
}
bool BensYesNo (std::string yn)
{
std::string str;
getline(std::cin, str);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::transform( yn.begin(), yn.end(), yn.begin(), ::tolower);
return str.compare(0, 1, "") == 0 && yn.compare(0, 1, "y") == 0 ||
str.compare(0, 1, "y") == 0;
}
int main()
{
const char *alist[] = { "yes", "no", "other", "" };
std::cout << " default answer results\n";
for (auto deflt : alist)
for (auto a : alist) {
answer = a;
std::cout << std::setw(9) << deflt << std::setw(9) << answer
<< " " << GetYesNo(deflt)
<< " " << BensYesNo(deflt) << "\n";
}
return 0;
}
The output is:
default answer results
yes yes 1 1
yes no 0 0
yes other 0 0
yes 1 1
no yes 1 1
no no 0 0
no other 0 0
no 0 0
other yes 1 1
other no 0 0
other other 0 0
other 0 0
yes 1 1
no 0 0
other 0 0
0 0
In every case, the two functions agree. (I've included some unusual
default strings, but that's because the test code is simpler that way.)
I take your point and I like your solution even though it doesn't
completely satisfy the requirements.
That may be, but I can't yet see what's missing. Can you give an example?