question about this if/else code using || and && - c++

#include <iostream>
#include <string>
using namespace std;
int main()
{
string vegetarian, vegan, gluten_free;
cout << "Welcome to Restaurant Selector!" << endl;
cout << "Are you a vegetarian?"<<endl;
cin >> vegetarian;
cout << "Are you a vegan?"<<endl;
cin >> vegan;
cout << "Are you gluten-free?"<<endl;
cin >> gluten_free;
if (gluten_free == "yes" && vegan == "yes" && vegetarian == "yes" )
{
cout<<"The Chef's Kitchen"<<endl;
}
else if (gluten_free == "yes" && vegan == "yes" )
{
cout<<"Vegan's lair"<<endl;
}
else if (gluten_free == "yes")
{
cout<<"Starbuck's"<<endl;
}
else if ( gluten_free == "no" || "No" && vegan == "no" || "No" && vegetarian == "no"||"No")
cout<<"Burger King"<<endl;
return 0;
}
How can I get the first if expression to use multiple variations of yes.
I want it to include: yes, Yes, and YES. however I can only use the or operator on two strings. I would also like to do this for the subsequent lines. What should I do?

How can I get the first if expression to use multiple variations of yes. I want it to include: yes, Yes, and YES.
Convert the input string to lower case before comparison.
A trivial example:
auto tolower = [](unsigned char c){
return std::tolower(c);
};
std::transform(
vegan.begin(),
vegan.end(),
vegan.begin(),
tolower
);
Note that simple string processing such as this work only with fixed width encodings and not with unicode.

Related

I need help on this C++ yes/no problem while using logical operators

So the problem is: Write a program that prints the question "Do you wish to continue?" and reads the input. If the user input is "Y", "Yes", "YES", then print out "Continuing". If the user input is "N" or "No", "NO" then print out "Quit". Otherwise, print "Bad Input". Use logical operators.
So far this is all the code that I have written. I know that it is not complete, and I do not know what else I need to add to the code.
#include <iostream>
using namespace std;
int main() {
char response;
cout << "Do you wish to continue?" ;
cin >> response;
if (response == 'Y'){
cout << "Continuing";
}
else if (response == 'N'){
cout << "Quit";
}
else if (response != 'N' || 'Y'){
cout << "Bad input";
}
return 0;
}
Update: so I edited my code and it is still giving me a bunch of errors. It's making me frustrated lol. Keep in mind I'm a beginner and we haven't learned loops yet. Sorry for the headache!
#include <iostream>
#include <string>
using namespace std;
int main() {
char response;
string help;
cout << "Do you wish to continue?" ;
cin >> response, help;
if (response == 'Y' || help == "Yes" || help == "YES"){
cout << "Continuing";
}
else if (response == 'N' || help == "No" || help == "NO"){
cout << "Quit";
}
else if (response != 'N' || response != 'Y' || help != "Yes" || help != "YES" || help != "No" || help != "NO"){
cout << "Bad input";
}
return 0;
}
First off I think this is a great start. Sounds like you are new to C++ so here are some suggestions:
1) Your response variable can only contain a character. I would suggest including string and changing the response to take a string from the user for 'Y', "Yes", etc.
2) I suggest wrapping your code in a while loop with an exit condition.
3) Each of your logic branches should include a return integer. This will give the program an exit condition if the logical conditions are met.
I know I haven't given you the answers fully. If you are truly stuck, reply back and we can walk through.
A simple way is to simply convert the user's answer to uppercase or lowercase. By doing this, you can simply use the lower case.
For your loop, you could for example use a "do..while".
#include <iostream>
#include <string>
using namespace std;
int main() {
int stop = 0;
string response;
//Continue until the user choose to stop.
do{
//-------------
// Execute your program
//-------------
cout << "Do you wish to continue? ";
cin >> response;
//-------------
//Convert to lower case
for (string::size_type i=0; i < response.length(); ++i){
response[i] = tolower(response[i]);
}
//-------------
//Check the answer of the user.
if (response.compare("y") == 0 || response.compare("yes") == 0){
cout << "Continuing \n";
}
else if (response.compare("n") == 0 || response.compare("no") == 0){
cout << "Quit \n";
stop = 1;
}
else{
cout << "Bad input \n";
}
}while(stop == 0);
return 0;
}
Like you said in the question, we care about Y,Yes,YES,N,No and NO. For anything else we need to print "Bad Input". Think about how you'd be storing these responses (hint: Sam Varshavchik's answer).
Once you've taken care of extracting user input, you'd want to check what the user actually entered and proceed accordingly. From your question it seems "if else" would do. You need to change the conditionals for your "if else ifs" because
you have 3 conditions for one type of response: Y, Yes and YES need one output - "continuing" while N, No and NO require a different output - "Quit" and for all others we print "Bad input". Think about what your conditionals should be and your if statement should look something like:
if (response == "Y" || response == "Yes" || response == "YES")
and then handle the case accordingly. You'd want to do the same for your No conditions and finally handle the case for all others. I'd suggest having your code like so:
if( conditionals for Yes){
//Code for Yes input
}
else if( conditionals for No){
//Code for No input
}
else{
//Code for all other inputs
}
It is tempting to give you the full answer but think about how your program needs to flow and proceed from there, you've almost got it!
If you have more questions post here and we'd be glad to help!

c++ if specific words from string

I'd like to check in an if statement for several words from a defined string (cin), so that it accepts different using of capital and small initial letters .
#include <iostream>
using namespace std;
int main()
{
string BothMods;
cout << "Are both online?" << endl;
cin >> BothMods;
if (BothMods == "Yes", "YES", "yes"{
cout <<"Both are online" << endl;
...
But when I type in one of the three conditions, the condition is always false (else gets executed). If I only use one (like if (BothMods == "Yes") ) it works.
You need to check each case individually using the OR operator if you want to check more than one case.
if (BothMods == "Yes" || BothMods == "YES" || BothMods == "yes") {
// do whatever
}

Get yes/no in console always fails

I'm trying to make a program that will run over and over again, provided the user says yes every time. Unfortunately, it doesn't seem to recognize when I input yes or no into it, and always does the default "Come again?" message. This is the code I'm using to get the input from the console:
bool getYN(){
bool confirmed = 0;
bool answer = 0;
string input;
while(!confirmed){
getline(cin, input, '\n');
transform(input.begin(), input.end(), input.begin(), toupper);
if(input.c_str() == "Y" || input.c_str() == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input.c_str() == "N" || input.c_str() == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
} else { //If the user says something else entirely
printf("\nCome again? (Y/N) ");
};
};
return answer;
};
I have included <string> and <algorithm>. For some reason, it always acts like it's not getting y/yes or n/no when I type them in. It just keeps asking me to answer again.
if(input.c_str() == "Y" || input.c_str() == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input.c_str() == "N" || input.c_str() == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
}
You should not be doing c-string comparisons like this. You're taking the address of a char and comparing against the address of a text-allocated object. Of course the comparison is going to return false.
With c++ strings, simple operator== comparisons are valid:
if(input == "Y" || input == "YES"){ //If the user says yes
confirmed = 1;
answer = 1;
} else if(input == "N" || input == "NO"){ //If the user says no
confirmed = 1;
answer = 0;
}
#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true; // breaks the loop
}
if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = false;
}
}
return 0;
}
You can use the above example to eliminate a huge portion of unnecessary code, I chose not to add the else statement but it will work if you add that here as well.
You can also condense this code even further but this was only intended to be a simple example as to how to better get this working for you!
As it was said above you can use == to compare the strings, if you're coming from certain other languages it can be an annoying change to get used to lol.
I have included string and algorithm. For some reason, it always acts like it's not getting y/yes or n/no when I type them in. It just keeps asking me to answer again.
algorithm is not required for what you're trying to do, and your making the reading and acceptance of the string input much more difficult than it needs to be.
If you look above you'll see the string input; This is going to be your variable that you can use to store the user input string into.
You'll also notice getline(cin, input); This is what you can use to "read" the string that the user enters when they're prompted to.
#Kelvin Shadewing My initial answer was only directed at your Question, this next example is directed to your comment to me below!
So you've got quite a few options but assuming that you want the user to input either yes or no and depending on the input you want to produce a specific result while ensuring that the user is prompted over and over again to input either yes or no all you have to is modify my original answer like so.
#include <iostream>
#include <string>
using namespace std; // For speed
int main()
{
bool saidYes = false;
string input;
while (!saidYes)
{
cout << "Input yes or no: ";
getline(cin, input);
if (input == "no" || input == "n" || input == "NO")
{
saidYes = true;
cout << "you said no" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else if (input == "y" || input == "Y" || input == "yes" || input == "YES")
{
saidYes = true;
cout << "You said yes" << endl;
/* breaks the loop by changing the
bool (true or false flag) to true, if you want to produce a specific result,
whether it's a simple output statement or a function call you can put it here
*/
}
else saidYes = false;
}
return 0;
}
I've modified my code based on the current best answer, but I've also optimized it so that confirmed is no longer necessary.
bool getYN(){
bool answer = 0;
string input;
while(!answer){
getline(cin, input, '\n');
transform(input.begin(), input.end(), input.begin(), toupper);
if(input == "Y" || input == "YES"){
answer = 2;
} else if(input == "N" || input == "NO"){
answer = 1;
} else {
printf("\nCome again? (Y/N) ");
};
};
return answer - 1;
};
Small optimization, sure, but every little bit counts.

My else if statement using a string is not working [duplicate]

This question already has answers here:
if statement not working right?
(5 answers)
Closed 7 years ago.
after a good amount of time trying to get my else if statement to work, it just doesn't. This program keeps returning the first one, no matter what I input. Please help.
#include <iostream>
#include <string>
using namespace std;
string arehap;
int main()
{
cout << "Are you happy?" << endl;
cin >> arehap;
if (arehap == "Yes" || "Y")
{
cout << "Good." << endl;
}
else if (arehap == "No" || "N")
{
cout << "Bad." << endl;
}
return 0;
}
You should use this:
if (arehap == "Yes" || arehap == "Y")
{
cout << "Good." << endl;
}
else if (arehap == "No" || arehap == "N")
{
cout << "Bad." << endl;
}
When you're using the || operator, you have to compare two boolean values. If arehap is equal to "Y", the following statement will be True: arehap == "Y". In that case your computer will "understand" this as if (True || False) { /* do smth */} and this will evaluate to True and the code you want to execute will be run.
Your problem lies in this line:
if (arehap == "Yes" || "Y")
C++ understands this as
if ((arehap == "Yes") || ("Y"))
and while the first check (arehap == "Yes") might be false, the second check -- which is just "Yes" is always true.
This happens, because the "Yes" gets understood as a char const* -- and this pointer must obviously not be NULL, but point to the character 'Y'!

using user input such as YES and NO to control program flow in C++

I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}