If statement does not read char variable properly [closed] - c++

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;
}
}

Related

Why are my or operators not working as intended?

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;
}

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

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.

C++ 'else' in loops

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.

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;
}