Why are my or operators not working as intended? - c++

My if statements are getting hit no matter the input. I can't wrap my head around why. Here is the code:
void Novice::selection()
{
char selection, shift;
cout << "Please select a section to run: A - Home Row, B - Bottom Row, C - Top Row, D - Pointer Fingers, E - Right Pinky;" << endl;
cin >> selection;
selection = toupper(selection);
if (selection != 'A' || 'B' || 'C' || 'D' || 'E') {
cout << "Invalid Input. Please select again" << endl;
cin >> selection;
}
if (selection == 'A' || 'B' || 'C') {
cout << "you're here" << endl;
}
If input is 'A', the first if statement triggers, if I then put in A again second if statement triggers as well. Any help would be appreciated.

This is not how logical operators work in c++. To compare against multiple values, you need to do:
if (selection == 'A' || selection == 'B' || selection == 'C') {
// ...
}
Note that your first if is incorrect, even if you use the fix above. If you check whether a value is not equal to several other values, this will always be true. That condition probably needs to be something like:
if (selection != 'A' && selection != 'B' &&
selection != 'C' && selection != 'D' && selection != 'E') {
// ...
}
Alternatively, for the first if condition, you can use a switch statement, like this:
switch ( selection )
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
break;
default:
cout << "Invalid Input. Please select again" << endl;
cin >> selection;
}

Related

why is else if function is not working in rock, paper, scissor?

I was asked to make a simple game of rock, paper, scissors in C++ but it turns out that my else if logic is not working. What do you think went wrong?
cout << "choose your pick..." << endl;
cout << "PRESS [ B ] if BATO(ROCK),[ G ] if GUNTING(SCISSOR) or [ P ] if PAPEL(PAPER) " << endl;
cin >> pick;
cin >> picke;
if ( (pick==picke) || (pick=='b' && picke=='B')
|| (pick=='B' && picke=='b') || (pick=='g' && picke=='G')
|| (pick=='G' && picke=='g') || (pick=='p' && picke=='P'))
{
cout << "SORRY TIE";
}
else if (pick=='p' || 'P' && pic­ke=='b' || 'B')
{
cout << "player 1 paper wins";
}
else if (pick=='b' || 'B' && pic­ke=='g' || 'G')
{
cout << "player 1 rocks wins";
}
else if (pick=='g' || 'G' && pic­ke=='p' || 'P')
{
cout << "player 1 scissor wins";
}
else if (pick=='b' || 'B' && pic­ke=='p' || 'P')
{
cout << "player 2 paper wins";
}
else if (pick=='g' || 'G' && pic­ke=='b' || 'B')
{
cout << "player 2 rocks wins";
}
else if (pick=='p' || 'P' && pic­ke=='g' || 'G')
{
cout << "player 2 scissor wins";
}
return 0;
Comparing like this: pick=='p' || 'P' && pic­ke=='b' || 'B' is pretty much useless. This is because the if statements condition will always be true. Why? Let me explain.
You cannot compare and check if pick contains either 'p' or 'P' like that. It sounds right in words but in C++ it is wrong. This is because in programming terms, it's like "is pick equal to 'p' OR is 'pick' equal to 'P'". You need to tell the compiler that you're checking if "is this equal to this". Not "is this equal to this and this" (like what you have right there).
If you have something like ... || 'p' && ..., it'll always be true, because the value of 'p' is not 0, meaning its true in boolean terms.
So to resolve this, we need to say "is pick equal to 'this'" every time we compare. So it may look like this,
//...
else if ((pick == 'p'|| pick == 'P') && (pic­ke == 'b'|| picke == 'B'))
{
cout << "player 1 paper wins";
}
else if ((pick == 'b'|| pick == 'B') && (pic­ke == 'g'|| picke == 'G'))
//...
Or else you can use tolower or toupper as #mch commented, to convert all the characters to a single case. It'll be easier and more efficient when comparing.
Note: It's better if you use brackets to segment the comparisons because it will not only will be easier to understand, it'll be correct logically too.

Fixing uninitialized local variable error

I am working on a project right now and when I try to run what I have below it gives me an error that says "uninitialized local variable 'userOption' used" on line 22, while (isValidOption(userOption) == true) {.
How do I fix that error? Thank you.
#include<iostream>
#include <string>
using namespace std;
char toupper(char ch) {
if (ch >= 'A'&&ch <= 'Z')
return(ch);
else
return(ch - 32);
}
bool isValidOption(char ch) {
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X')
return(true);
else
return(false);
}
char getMainOption() {
string UserInput;
char userOption;
while (isValidOption(userOption) == true) {
cout << "Choose One of the following options\n";
cout << "I--List Our Inventory\n";
cout << "O--Make an Order\n";
cout << "L--List all Orders made\n";
cout << "X--Exit\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
if (!isValidOption(userOption)) {
cout << "Invalid String\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
}
if (userOption == 'I')
cout << "Listing Our Inventory\n";
else if (userOption == 'O')
cout << "Make an order\n";
else if (userOption == 'L')
cout << "Listing all orders\n";
}
return userOption;
}
int main() {
char choice;
choice = getMainOption();
system("pause");
return 0;
}
What the error is saying that you're trying to read from userOption before you've ever written to it. If a variable is uninitialized, its memory contents will be full of junk left behind by other functions and it can easily cause bugs. In your case, you'll want to read input from the user into userOption before you do any logic on it. This can be done with a do-while loop:
char userOption; // not yet initialized
do {
...
cin >> userOption; // userOption gets initialized here on first loop run
} while (isValidOption(userOption)); // no need for == true, that's a tautology :-)
// NOTE: perhaps you want to loop while the input is INvalid, as in
// while (!isValidOption(userOption)); ?
A couply code-review comments I would additionally give are:
std::toupper already exists in <cctype>. Docs are here
return is not a function call and it's better to write return ch; than return(ch);
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; } is completely equivalent to the shorter return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X';
Also take a look at system(“pause”); - Why is it wrong?
Happy coding! Let me know if questions remain

If statement does not read char variable properly [closed]

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 5 years ago.
Improve this question
When calling the programs starLeftTriangle & starRightTriangle, the if statements seem to ignore the variable choice and the program continuously runs as if the choice is 'l' or 'L'.
Any idea why the if statements are being ignored? I've omitted the actual code for the programs.
#include <iostream>
using namespace std;
void starLeftTriangle(int n);
void starRightTriangle(int n);
int main() {
int star;
char choice;
cout << "Input the number of stars you want to draw: \n";
cin >> star;
cout << "Would you like to draw a left triangle, right triangle, or quit? \n";
cin >> choice;
cout << "The choice value is " << choice << endl;
system("pause");
while (choice != 'q' || 'Q'){
if (choice == 'l' || 'L'){
starLeftTriangle(star);
}
else if (choice == 'r' || 'R') {
starRightTriangle(star);
}
}
if (choice == 'q' || 'Q') {
cout << "Quitting Program.";
}
else{
//throw error
}
return 0;
}
You need to express an equality/inequality for each term in your while and if conditions:
while (choice != 'q' && choice != 'Q') {
if (choice == 'l' || choice == 'L') {
starLeftTriangle(star);
}
else if (choice == 'r' || choice == 'R') {
starRightTriangle(star);
}
}
if (choice == 'q' || choice == 'Q') {
cout << "Quitting Program.";
}
else {
// throw error
}
What I think is currently happening is that for some value of choice the following if condition is always coming up true:
if (choice == 'l' || 'L') {
starLeftTriangle(star);
}
The reason for this is if choice in fact be 'l' then this will be true, but if not, your other condition is 'L', which will also evaluate to true. To avoid this, use equalities everywhere.
Your condition is being interpreted as follows: choice == 'q' OR 'Q' - integer code of Q is more than 0, so it will always return true for any character in compraison
Try this one:
bool loop = true;
while (loop) {
switch ((int) choice) {
case (int) 'l':
case (int) 'L':
starLeftTriangle(star);
break;
case (int) 'r':
case (int) 'R':
starRightTriangle(star);
break;
case (int) 'q':
case (int) 'Q':
loop=false;
break;
}
}

C++ while statement, with nested if else

I have been having an issue getting the if else statement to properly work in the code.
I have everything else where I need it, just we are supposed to have multiple entries input and it just automatically uses the responses and the else statements do not work.
int main ()
{
string dep = "Deposit";
string with = "Withdrawl";
string bal = "Balance";
char choice;
cout << "PLease enter options A, B, C, or Q to quit.\n";
cin >> choice;
switch (choice) //to make them all the same, same as using toUpper
{
case 'a':
case 'A':
cout << "";
break;
case 'b':
case 'B':
cout << "";
break;
case 'q':
case 'Q':
cout << "";
break;
}
int count = 1;
while (count <= 4)
{
if (choice == 'a' || 'A' )
cout << dep << endl;
else if (choice == 'b' || 'B' )
cout << with << endl;
else if(choice == 'c' || 'C' )
cout << bal << endl;
else
(choice !='a' && choice !='b' && choice !='c');
cout << "that is invalid, PLease enter options A, B, C, or Q to quit.\n";
++count ;
}
system ("PAUSE");
return 0;
}
You need to fix the conditional statements like this:
if (choice == 'a' || choice == 'A' )
What you have will always result in the first conditional being met because 'A' is equal to decimal 65.
if(choice == 'a'||'A'),the computers will run the 'a'||'A' first,and it's return 1 (in bool) ,and then run the
choice == 1,according to your codes, there are no choice == 1,so the codes in if will not be run.

if statements with char values

So I'm trying to write an easy basic game here with basic C++, and when I try to execute this
// global variabless
const char UP = 'w', LEFT = 'a', DOWN = 's', RIGHT = 'd'; // player movement choices
char playerMove; // goes with askPlayer
void askPlayer()
{
char choice;
cout << "Use the WASD keys to move: ";
cin >> choice;
int worked;
do{
if (choice == 'w' || choice == 'W')
{
playerMove = UP;
worked = 1;
}
else if (choice == 'a' || choice == 'A')
{
playerMove = LEFT;
worked = 1;
}
else if (playerMove == 's' || playerMove == 'S')
{
playerMove = DOWN;
worked = 1;
}
else if (playerMove == 'd' || playerMove == 'D')
{
playerMove = RIGHT;
worked = 1;
}
else
{
cout << "Invalid entry." << endl;
worked = 0;
}
} while (worked != 1);
return;
}
It works up to the user entering a letter. Xcode says (lldb) then the page fills up with numbers, and after you stop the run, it says "Program ended with exit code: 9". It does this even if you enter one of the valid values
You never prompt for another value after the user enters the first one:
cin >> choice; // <==
int worked;
do {
// ..
} while (worked != 1);
Just move the input into the loop:
int worked;
do {
cin >> choice; // possibly with cout prompt too
// rest as before
} while (worked != 1);
Your input is outside the loop, your variable worked is uninitialized ( though it is not a error in your code but is cleaner to initialize your variables) and it should have bool type. Whole code can be simplified by the switch statement:
void askPlayer()
{
do {
char choice;
cout << "Use the WASD keys to move: ";
cin >> choice;
switch( choice ) {
case 'w' : case 'W' :
playerMove = UP;
break;
case 'a' : case 'A' :
playerMove = LEFT;
break;
case 's' : case 'S' :
playerMove = DOWN;
break;
case 'd' : case 'D' :
playerMove = RIGHT;
break;
default:
cout << "Invalid entry." << endl;
continue;
}
} while( false );
return;
}