Better methods to apply operator "and &&" "or || " C++ - c++

Question: Is there a more efficient method to using operator or "|| " than what I'm using?
I'm creating the HangMan Game in which players type a letter and the only way to get out of the loop is by entering the correct word in which this case if statement is the only way out.
I'm running into a problem with my compiler, maybe is that i need to work on a better and cleaner version of my code but here is what I'm currently have so far...
// w is the word chosen
if(w1=='d' && w2=='u' && w3=='c' && w4=='k' || answer == error)
{
if(w1=='d' && w2=='u' && w3=='c' && w4=='k')
{
cout << "The word is correct \n";
}
else if (answer == error)
{
cout << " You got 5 strike you lost \n";
}
}
I'm currently using Qt Project Compiler in Ubuntu to Compile my C++ Program.
I don't have this error/ suggestion with Gcc g++ on the Command Line
/home/cristian/Qt_Programs/Hangman_Game/main.cpp:123: warning: suggest parentheses around '&&' within '||' [-Wparentheses]

You don't need the first if statement. The second if-else will accomplish the same with or without it. That should remove the compiler suggestion.
if (w1 == 'd' && w2 == 'u' && w3 == 'c' && w4 == 'k') {
cout << "The word is correct \n";
}
else if (answer == error) {
cout << " You got 5 strike you lost \n";
}

Related

C++ Blackjack code only going to first if statement

I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the user to try again.
I'm still fairly new to C++, so some help would be appreciated.
while (repeat == 0)
{
char hitStand;
cout << "Would you like to HIT or STAND [H/S]";
cin >> hitStand;
if (hitStand = "H" || "h")
{
PcardNew = rand() % 13 + 1;
cout << endl;
cout << "Your new card is: " << PcardNew << endl;
if (PcardNew > 10)
{
PcardNew = 10;
}
playerTotal = playerTotal + PcardNew;
cout << "Your new total is: " << playerTotal << endl;
}
else if (hitStand = "S" || "s")
{
break;
}
else
{
cout << "Please enter a valid imput [H/S]" << endl;
}
}
There are (at least) three errors in the single if (hitStand = "H" || "h") line!
First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator.
Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of characters. Use single quotes for single characters (thus, 'H' and 'h').
Third, you can't compare one object with two others like that with a logical or (||) operator. You need to make two separate comparisons and then or the results of each:
So, use this:
if (hitStand == 'H' || hitStand == 'h')
{
//...
And similarly for your second test:
else if (hitStand == 'S' || hitStand == 's')
{
//...
That is because your condition in if statement is always true. Since "h" is in or (||).
Instead use:
if (hitStand == 'H' || hitStand == 'h')
and
else if (hitStand == 'S' || hitStand =='s')

While Loop when to use OR or AND? [duplicate]

This question already has answers here:
While loop with multiple conditions in C++
(4 answers)
Closed 2 years ago.
I need help with this simple question.
I'm starting to learn more about while loops and I'm not sure what I'm doing wrong.
Here's a snippet of the code that I'm working on, so when I'm using or in while loop the loop executes indefinitely. But when I use AND the loop stops can somebody please explain? Shouldn't OR be used instead as per definition?
void displayMenu() {
char option;
while (option != 'Q' or 'q') { //And or OR?
cout << "P - Print numbers" << endl;
cout << "A - Add a number" << endl;
cout << "M - Display mean of the numbers" << endl;
cout << "S - Display the smallest number" << endl;
cout << "L - Display the largest number" << endl;
cout << "Q- Quit" << endl;
cout << "Choose Your Option-" << endl;
cin >> option;
if (option == 'P' or 'p')
Print();
}
}
You have phrased your condition (option != 'Q' or 'q') like you speak it.
"option not upperQ or lowerQ".
That is understood by the compiler as "option is not upperQ; or q", where "q" is a non zero thing. Nonzeros are interpreted as "true". So the whole thing always evaluates to "true", always, even for option having a values like 'Y' or '2'.
You have to rephrase much less coloqually as
"option is not 'Q' and it is not 'q' "
and you have to use the appropriate operators. Using additional () to make sure that what you mean is understood does not hurt.
That is done as
( (option != 'Q') && (option != 'q') )
Using or, or in this case and instead of the logical && is possible in certain situations, and the additional () are not required either. The main issue is however with your choice of "or" instead of "and" and using the () is a safe way as long as you are not very familiar with the operators and their order of evaluation in expressions like this one.
Why exactly you need to use && ("and") instead of or or || is a question of what happens with the two interesting letters. Lets take 'Q' it obviously is one of the two you are looking for. But it is not 'q'. So the second part of the condition with is true. With || that is sufficient and the whole thing is evaluated to "true" and the loop continues - obviously not what you want. The same is for 'q', it is not 'Q' and there for || continues.
What you actually want is "neither" and that is the same as "not this and not that". Hence you need "not and not", !a && !b or more bluntly explicit (option != 'Q') && (option != 'q').
That can be reprhased with implicit knowledge of operator precedence (look it up and try to memorize) to option != 'Q' && option != 'q'.

Why does my function get read, but become an infinite loop? [duplicate]

This question already has answers here:
If statement runs through whether conditions are met or not
(4 answers)
Closed 2 years ago.
Hello I'm having a problem where when I call my function after the user enters "Y" to start the game, the cout gets read but it becomes an infinite loop. It works just fine when you enter "N" or something thats not supposed to be entered. I am using a header file called functions to well, put all the functions if that has anything to do with it. I am still in the very early learning stages of programming, and run into so many speed bumps and just not quite sure where to turn. Any help is appreciated. (P.S. I have not yet started on the gameStart() function just because of this problem. That's not whats it's going to be in the end.)
#ifndef FUNCTIONS_H;
#define FUNCTIONS_H
#include <iostream>
using namespace std;
void startScreen()
{
void gameStart();
char answer;
cout << "Welcome to __________\n\n";
cout << "This is my fisrt ever actual program I made out of my own free will lol.\n";
cout << "It is a Text-Based Adventure game. In this game you will make a character,\n";
cout << "and explore the land of Spelet, battling enemies, leveling up, getting loot,\n";
cout << "and learning skills! You do not need to capitalize anything but your character\n";
cout << "name. If a question has (something like this), those are the choices for that \n";
cout << "interaction! Thank you for trying out my terrible little game! :)\n";
cout << "I really hope y'all enjoy it!\n\n";
cout << "Would you like to play?\n";
cin >> answer;
do
{
if (answer == 'Y' || answer == 'y')
{
gameStart();
}
else if (answer == 'N' || answer == 'n')
{
cout << "Program will now close...\n";
system("pause");
exit(0);
}
else
{
cout << "Enter a Y for yes or an N for no.\n";
cout << "Would you like to play?\n";
cin >> answer;
}
}
while (answer != 'N', 'n' || 'Y', 'y');
}
void gameStart()
{
cout << "\n\"BOOM-BOOM-BOOM...\"\n\n" << endl;
}
#endif
maybe you need:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y')
The comma operator doesn't do what you think it does. It "discards the result," as my link says.
You want the && operator (AND operator) instead:
while (answer != 'N' && answer != 'n' && answer != 'Y' && answer != 'y');

Input not being read properly by if condition statement

one would think this is easy, but for some odd reason, my conditional statement is ignoring user input.
If I input a character 'N' or 'n' it still executes the 'Y' portion of the conditional statement, have a look:
while (i < 10) {
cout << "Would you like "<< nameOfDish[i] << "? Please enter Y or N.\n";
cin >> userResponse;
if (userResponse == 'y' || 'Y')
{
cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
cin >> quantityOfDish[i];
if (quantityOfDish[i] == 0) {
cout << "I suppose you're entitled to change your mind.\n";
}
else if (quantityOfDish[i] < 0) {
cout << "Your generosity is appreciated but I must decline!\n";
quantityOfDish[i] = 0;
}
i++;
}
else if (userResponse == 'n' || 'N')
{
i++;
}
else
{
cout << "I think you mumbled NO, so I'll just go on.\n";
i++;
}
}
Is there any particular reason why despite inputting 'n' it still goes into the 'Y' if conditional block?
I have stepped through the code in the debugger, and I noticed that the userResponse variable is being read in properly. Yet, the if condition does not seem to be working properly. Thanks!
This statement (and your other if statement) is not doing what you think it does:
if (userResponse == 'n' || 'N')
Try this instead:
if (userResponse == 'n' || userResponse =='N')
You need to define each logical operation individually in a condition check. You will have to compare userResponse with n and N separately.
if (userResponse == 'y' || userResponse == 'Y')
{
cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
cin >> quantityOfDish[i];
if (quantityOfDish[i] == 0) {
cout << "I suppose you're entitled to change your mind.\n";
}
else if (quantityOfDish[i] < 0) {
cout << "Your generosity is appreciated but I must decline!\n";
quantityOfDish[i] = 0;
}
i++;
}
It's been awhile since I worked in C++, but I'm fairly sure I know what's going on.
The || operator does not work on a single conditional, there must be two complete conditionals, one on each side. Try replacing your if statement with this line:
if (userResponse == 'y' || userResponse == 'Y')
Maybe you are used to SQL? You need to repeat the userResponse
if userResponse == 'n' || userResponse == 'N'
Otherwise you are actually testing
if userResponse is 'n' or the char'N' exists
The error in this code is, as others have pointed out, the if statement. However, I feel this may need some clarification. Every C++ expression returns a value. For example.
userResponse == 'y'
returns the value 1 if userResponse is 'y' and 0 if it is anything else. The operator || returns 1 if either the left or the right expression is non-zero.
Finally, the if statement checks to see whether or not the expression is zero or non-zero. So,
if (5)
cout << "X";
else
cout << "Y";
will print X and
if (0)
cout << "A";
else
cout << "B";
will print B.
Now, we can begin to understand why your code compiled successfully, but didn't do what you wanted it to.
if (userResponse == 'y' || 'Y')
In this example, the || operator will always return 1 because the expression on the right, 'Y', will always be non-zero (specifically, it will be 89, since C++ characters are just aliases for their ASCII corresponding number). And of course,
if (userResponse == 'y' || userResponse == 'Y')
work as intended. But there is a much better solution and that would be the switch statement, whose purpose is to handle situations like this. Here it is in action:
switch (userResponse) {
case 'y':
case 'Y':
//The user answered yes, handle that situation here.
break;
case 'n':
case 'N':
//The user answered no, handle that situation here.
break;
default:
// The user did not enter a valid answer,
// handle that situation here.
break;
}

How to take a word from a file, and store it in a variable? C++

I have made a simple Rock, Paper, Scissors game in C++ Console Application. The game so far, worked great.. until I tried storing a word from a file, inside a variable, and then trying to use that variable in IF statements.
Here's how I store my word from the file, in a variable.
string comp_selection;
char player_selection;
And here's the part of the code where I am trying to get it to work.
cout << "Rock, Paper, or Scissors?";
cin >> player_selection;
if (comp_selection =='r' || comp_selection == 'R')
{
if (player_selection == 'r' || player_selection == 'R')
{
cout << "Computer chose " << comp_selection << "... It's a draw!" << std::endl;
}
else if (player_selection == 'p' || player_selection == 'P')
{
cout << "Computer chose " << comp_selection << "... You win!" << std::endl;
}
else if (player_selection == 's' || player_selection == 'S')
{
cout << "Computer chose " << comp_selection << "... You lose!" << std::endl;
}
}
The output should be:
Computer chose Rock... You win!
If the player chose Paper for example.
Instead, I get this error message
Severity Code Description Project File Line Suppression State
Error C2678 binary '==': no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)
Any help or guidance, would be great! Many thanks in advance.
Your comp_selection is defined as a std::string, but you are comparing it against a char ('r', etc). You should compare it against another string ("r") or just redefine comp_selection to be a character:
char comp_selection;
char player_selection;
In C++, a single character is denoted by single quotes ('c') whereas a string of characters is denoted by double quotes ("full string").
So far, you have been enjoying cin >> overloading recognizing that it's writing to a char. When reading from a file, you've apparently utilized a string. This is fine, except now the compiler is complaining that it does not know how to compare a string and a char. In short, your types don't match.
You can compare only first character of comp_selection (comp_selection[0])
if (comp_selection[0] =='r' || comp_selection[0] == 'R')
{
It is not the best solution but it requires the minimum code changes...
I've just realised that my code does what it was intended to do! By setting my
comp_selection to char, like someone here suggested, I can manually input what the computer chose by using the IF Statements.
For example:
if (comp_selection == 's' || comp_selection == 'S')
{
if (player_selection == 'r' || player_selection == 'R')
{
cout << "Computer chose Scissors... You win!" << std::endl;
}
else if (player_selection == 'p' || player_selection == 'P')
{
cout << "Computer chose Scissors... You lose!" << std::endl;
}
else if (player_selection == 's' || player_selection == 'S')
{
cout << "Computer chose Scissors... It's a draw!" << std::endl;
}
}