What would the best way be of reducing my conditions in this code, is it to simply implement the Boost library for a string comparison or is there another way of doing it? I would much more prefer to avoid using boost if possible.
How could said question be implemented on the following code?
cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question; cin >> question;
if (question == "yes" || question == "Yes" || question == "Y" || question == "y" || question == "YEs" || question == "YES" || question == "yeS" || question == "yES")
{
cout << "You said yes!" << endl;
return 1;
}
else if (question == "No" || question == "NO" || question == "nO" || question == "N" || question == "n")
{
cout << "You said no!" <<endl;
return 0;
}
else
{
AskAQuestion();
}
It might not be the most efficent solution but if you convert the entire string to lower case then you only need to check against the word and the letter instead of all the possible permutation. So if you have
void make_lowercase(std::string& data)
{
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
Then
cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question; cin >> question;
if (question == "yes" || question == "Yes" || question == "Y" || question == "y" || question == "YEs" || question == "YES" || question == "yeS" || question == "yES")
//...
Becomes
cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question;
cin >> question;
make_lowercase(question);
if (question == "yes" || question == "y")
//...
The following does not do exactly the same since you did not check 'yEs' as a possible case in the first if statement, but this is probably along the lines what you are looking for. It is based on lower casing the answer of the user first before checking the answer, to reduce the number of cases to check.
#include <algorithm>
#include <cctype>
...
std::cout << "Please Enter An Answer Of Yes(Y) or No(N): ";
std::string answer; std::cin >> answer;
std::transform(answer.begin(), answer.end(), answer.begin(), std::tolower);
if (answer == "yes" || answer == "y")
{
std::cout << "You said yes!\n";
return 1;
}
else if (answer == "no" || answer == "n")
{
std::cout << "You said no!\n";
return 0;
}
else
{
AskAQuestion();
}
I took the liberty of renaming question to answer, seems more logical in this context.
Related
This question already has answers here:
Can you use 2 or more OR conditions in an if statement? [duplicate]
(9 answers)
Closed 2 years ago.
cout << "Are you driving a vehicle onto the ferry? (y/n) ";
cin >> vehicle;
if (vehicle == 'y' || vehicle == 'Y') {
cout << "What is the length of the vehicle in feet? ";
cin >> vehicleLength;
if (vehicleLength > 20) {
extraLengthCharge = (vehicleLength - 20) * extraLengthPrice; }
cout << "Is the vehicle over 7 feet high? (y/n) ";
cin >> vehicleHeight;
if (vehicleHeight == 'y' || 'Y') {
vehiclePrice = 69.00, fuelSurcharge = 10.40;
} else if (vehicleHeight == 'n' || 'N') {
vehiclePrice = 43.00, fuelSurcharge = 4.15;
}
else if (vehicle == 'n' || vehicle == 'N') {
vehiclePrice = 0, fuelSurcharge = 0; }
}
My code will give me the correct 'fare' if the response is yes, but if I type in no it will still assign the 'yes' value. I assume it has something to do with my else if statement format for vehicleHeight.
Thanks and sorry for the novice question.
The conditions vehicleHeight == 'y' || 'Y' and vehicleHeight == 'n' || 'N' will be always true because 'Y' and 'N' will be always true and logical OR is used with them.
You should use conditions vehicleHeight == 'y' || vehicleHeight == 'Y' and vehicleHeight == 'n' || vehicleHeight == 'N' like what you used in other if statements instead.
This question already has answers here:
How to compare multiple strings inside an if statement?
(6 answers)
Closed 5 years ago.
My program keeps looping and never get's to "return 0;". Is it the compiler that's bad or the code?
#include<iostream>
using namespace std;
int main() {
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" << endl;
while(Input =="Yes" || "yes"){
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
cout << "Let's begin!";
return 0;
}
The expression Input == "Yes" || "yes" is evaluated, due to operator precedence, as
(Input == "Yes") || "yes"
which is always true. This is because the const char[4] literal "yes" decays to a const char* type, with a non-zero pointer value.
You need Input == "Yes" || Input == "yes"
My program keeps looping and never get's to “return 0;”. Is it the compiler that's bad or the code?
The code, as (almost) always.
Input =="Yes" || "yes" will always evaluate to true, no matter what Input's value really is, since it boils down to saying:
true if: Input equal to "Yes" OR "yes".
false if otherwise.
A string literal evaluates to true, thus the second operand of the logical or will be true, causing the whole logical expression to evaluates to true, always!
As a result your while loop's condition is always true, resulting in an infinite loop!
So change this:
while(Input =="Yes" || "yes")
to this:
while(Input =="Yes" || Input == "yes")
PS: Change the condition of the if statement similarly, since it's the same exact condition.
Your while statement's condition is wrong:
while (Input == "Yes" || "yes")
as "yes" operand always evaluates to true causing the entire condition to be true. Try this instead:
while (Input == "Yes" || Input == "yes")
There is a silly mistake in your code. Please see the below edited code -
#include<iostream>
using namespace std;
int main(){
string nameInput = "";
string Input = "Yes";
cout << "Welcome to the purple casino!" << endl << "What's your name?" <<
endl;
while(Input =="Yes" || Input == "yes"){ // Error was here
getline(cin, nameInput);
cout << nameInput << ", what a nice name!" << endl << "Do you want to
change it?" << endl;
getline(cin, Input);
if(Input =="Yes" || "yes"){
cout << "To what?" << endl;
}
}
<< "Let's begin!";
return 0;
}
Try modifying while(Input =="Yes" || "yes"){ to while(Input =="Yes" || Input == "yes"){
I think the problem will be solved.
Hi before return try :
cout << "Let's begin!";
And change in While and if your condition to:
(Input =="Yes" || Input=="yes")
In a more general way, if you have a loop from which your program never returns, it means that the condition you passed always evaluates to true.
In your case indeed, an as others already answers, the condition
while (Input == "Yes" || "yes")
always evaluate to true because of the second part.
What you really want is to check if Input is "Yes" OR Input is "yes", which in C++ should be written :
while (Input == "Yes" || Input == "yes").
Hope, this more general answer will help.
int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
cout << "No" << endl;
}
else {
cout << "I don't understand." << endl;
}
return 0;
}
int main() {
OnLoad();
system("pause");
return 0;
}
This code only returns Yes back, after the console window pops up and ask are you here to take over the city from zombies even after i type no it returns yes!
if (userInput == "yes" || "Yes")
actually means
if ((userInput == "yes") || ("Yes"))
It's logical OR between two expressions: userInput == "yes" and "Yes". The first one is correct and evaluates to bool directly. The second one is just a char* that will be converted to bool implicitly. Since it's a compile time string it cannot be nullptr, which means it will always evaluate to true. And that, in turn, means the whole condition is always true (that's how logical OR works).
The correct code is
if (userInput == "yes" || userInput == "Yes")
P. S. This is why I always recommend compiling with the highest warning level possible (/W4 for MSVC, -Wall -pedantic-errors for GCC and clang). Most compilers will generate a warning in this case.
that's not how the || operator works, if you just put "Yes" as a condition it will always evaluate to true
if (userInput == "yes" || userInput == "Yes") {
cout << "Yes" << endl;
}
the reason why is because of precedence
userInput == "yes"
and
userInput == "Yes"
get evaluated before || ( logical OR)
In C++, I have run into a problem when I am doing loops. I just know there is an obvious solution I am just overlooking in my work. Here is an example for reference:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string loop();
int main()
{
string answer;
do
{
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or no\n";
loop();
}
}while (answer == "yes" || answer == "Yes" || answer == "YES");
return 0;
}
string loop()
{
string answer;
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or no\n";
loop();
}
return answer;
}
When I am doing an If-else in a loop, I run into a problem when it comes to the else section. I cant seem to figure out how to display something that tells the user there is an error, and then re-run the same sequence. For example, in the program I included, when the user enters something other than yes or no, I am not sure how to show an error statement and then loop it back to the top so it asks the question again.
You should use a while loop.
string answer;
while ( (answer != "yes") && (answer != "no") ) {
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO") {
cout << "As you wish";
break;
}
if (answer == "yes" || answer == "Yes" || answer == "YES") {
cout << "";
break;
}
}
The problem isn't the loop; the problem is you've got your logic all tangled up. The solution isn't a way to fix the loop, the solution is a way to straighten up your logic.
A simple trick which is a lot more useful than it appears is to completely separate the loop from the thing you do in the loop:
// This function does something, then returns a boolean value
// to indicate whether or not you should continue looping.
bool do_something();
int main()
{
bool continue_looping = true;
while (continue_looping) {
continue_looping = do_something();
}
}
Now, you implement do_something() in a way that doesn't have to worry about actually doing the looping; it's only responsibility in that regard is to return a value that indicates whether looping should continue.
All you need is a single do-while loop...
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string ans{""};
transform(ans.begin(), ans.end(), ans.begin(), ::tolower); // convert string to lower case
do {
cout << "Do you wish to be asked this question again? ";
cin >> ans;
if (ans == "no") {
cout << "As you wish.";
} else
if (ans == "yes") {
cout << "";
}
else {
cout << "You didn't answer yes or no." << endl;
}
} while (ans != "yes" && ans != "no");
return 0;
}
Note, the transform algorithm converts the string into lower case to avoid variations in the spelling of yes and no.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have this program I am working on and for some reason the while loop is not running the way I intended/expected it to work.
#include <iostream>
using namespace std;
int main() {
const int size = 5;
char answer_sheet[size] = {'B','D','A','A','C'}; //'A','B','A','C','D','B','C','D','A','D','C','C','B','D','A'};
char student_answer[size];
char answer;
for(int i=0;i<size;i++)
{
cout << i+1 << ": ";
cin >> answer;
cout << endl;
while(answer != 'A' || answer != 'B' || answer != 'C' || answer != 'D')
{
cout << "You must enter either A, B, C, or D" << endl;
cout << i+1 << ": ";
cin >> answer;
cout << endl;
}
student_answer[i] = answer;
}
return 0;
}
I am entering a char A,B,C, or D and when I enter it the correct way I go into the while loop when I am not suppose to unless I enter the char incorrectly.
I can't seem to figure out the problem.
Thanks
answer != 'A' || answer != 'B' is always true, for any value of answer.
Did you mean && instead of ||?
You forgot C and D (probably a typo):
while(answer != 'A' || answer != 'B' || answer != 'A' || answer != 'B')
Maybe you want:
while (answer != 'A'
&& answer != 'B'
&& answer != 'C'
&& answer != 'D')
{
}
Another method:
const std::string allowable_answers = "ABCD";
//...
while (allowable_answers.find(answer) == std::string::npos)
{
// answer is not in the allowable set.
}
The condition you're looking for is
while(answer != 'A' && answer != 'B' && answer != 'C' && answer != 'D')
The || should be && in each case, and you should also never check for 'C' or 'D'
First, why don't you use a do/while loop instead of a while loop. Secondly, you have
while(answer != 'A' || answer != 'B' || answer != 'A' || answer != 'B')
{
cout << "You must enter either A, B, C, or D" << endl;
cout << i+1 << ": ";
cin >> answer;
cout << endl;
}
Shouldn't the program loop if A, B, C, D aren't input? You have this to loop if A, B, A, B isn't the answer. A do/while loop will enter the loop and continue the loop if the proper answer hasn't been input