Evaluating if statement with single char C++ - c++

I am trying to evaluate a single char:
bool repeat = true;
while (repeat)
//code
char x;
cout << "Would you like to tansfer another file? Y/N ";
cin >> x;
if (x == 'y' || x == 'Y')
repeat = true;
if (x == 'n' || x == 'N')
repeat = false;
else
throw "Input error";
I keep getting Input Error as my console output. Any ideas why? I can't get the while loop to repeat.

You are missing an else here:
if (x == 'n' || x == 'N')
should be:
else if (x == 'n' || x == 'N')
and you need to add braces after the while to encompass the input and if statements.

You forget braces {} after while:
while (repeat)
{
char x;
cout << "Would you like to tansfer another file? Y/N ";
cin >> x;
if (x == 'y' || x == 'Y')
repeat = true;
else
if (x == 'n' || x == 'N')
repeat = false;
else
throw "Input error";
}

Related

Why is my Else If 'vehicleHeight' code being ignored? [duplicate]

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.

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

Chars in do while loop conditions

I am having trouble with the last do while loop in my code. I have conditions set to stop the look when Y, N, y, or n are entered but even if those values are entered the loops continues to run and continue to ask for a Y or N. In debugging it seems that the Ascii value for the character is also stored in the variable? What do I need to change to have the do while loop end when there is an input of any of those 4 characters?
#include <string>
#include <iostream>
#include <iomanip>``
using namespace std;
int main()
{
int numberOfShapes, i, j, k, rectangleBase, rectangleHeight;
char star = '*';
char filled;
do
{
cout << "Enter the integer between 6 and 20 that you would like to be the base of the rectangle: ";
cin >> rectangleBase;
}while (rectangleBase < 6 || rectangleBase > 20);
rectangleHeight = rectangleBase / 2;
do
{
cout << "Enter the number of shapes you would like to draw(Greater than 0 and less than or equal to 10: ";
cin >> numberOfShapes;
} while (numberOfShapes <= 0 || numberOfShapes > 10);
do
{
cout << "Would you like a filled shape? [Y or N]: ";
cin >> filled;
} while (filled != 'Y' || filled != 'N' || filled != 'y' || filled != 'n');
Your loop end condition is wrong:
while (filled != 'Y' || filled != 'N' || filled != 'y' || filled != 'n');
consider that the value is 'y' then your condition will be:
(true || true || false || true)
which evaluates to true.
Change to:
while (filled != 'Y' && filled != 'N' && filled != 'y' && filled != 'n');
Then it will be:
-> 'y' (true && true && false && true) -> false
-> 'l' (true && true && true && true) -> true
You need to use && not ||:
} while (filled != 'Y' && filled != 'N' && filled != 'y' && filled != 'n');
If you write it as you say it, perhaps it would be more clear and will help to avoid these mistakes:
do
{
cout << "Would you like a filled shape? [Y or N]: ";
cin >> filled;
if (filled == 'Y' || filled == 'N' || filled == 'y' || filled == 'n')
break;
}
while (true);

Need to add a loop to exit or repeat in C++

I want to make a code that asks user for input either to quit or repeat. I am not getting the desired output.
int main()
{
char yes,yn;
do
{
cout << "Hello world!" << endl;
while(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
{
cout<<"enter (Y/N): ";
cin>>yes;
yn = yes;
}
}while(yn == 'y' || yn == 'Y');
}
Program asks for user input, when I input "Y,y,N or n", it should get out of the loop and then decide whether exit or repeat. But it isn't getting out of the loop and asking me for input again and again. I am not getting what is stopping to get out of the loop.
I didn't test, but your issue seems to be here:
while(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
This condition is always true (yet shouldn't). It should be :
while(yn != 'y' && yn != 'Y' && yn != 'n' && yn != 'N')
or
while(!(yn == 'y' || yn == 'Y' || yn == 'n' || yn == 'N'))
Moreover, yn isn't initiliazed, you may want to do a do { ... } while(...); again.
while(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
Is always true. It should be
while(yn != 'y' && yn != 'Y' && yn != 'n' && yn != 'N')
Firstly, this expression:
(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
is always true, as yn is always not equal to one of those things.
(yn != 'y' && yn != 'Y' && yn != 'n' && yn != 'N')
is probably what you meant.
Secondly, your life would be easier if you did
yes = toupper (yes);
(i.e. put it in upper case), then you'd only have to look for one thing.
Thirdly, and most seriously, your inner while examines the value of yes before it's been initialized. Either use a do while() construct, or intialize the value to something before the loop.
Fourthly, it's not clear what you are trying do to here. Do you really need two loops at all?
I think do while loop is all you need for the execution...
int main()
{
char yes,yn;
do
{
cout << "Hello world!" << endl;
cout<<"enter (Y/N): ";
cin>>yes;
yn = yes;
if(yn=='N'||yn=='n')
{
break;
}
}while(true);
}
your loop does not exit becuse your while loop is always true..
while(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
Now I have added a break statement in your loop on a if condition and changed the do while condition
in this case it will run the loop on any condition and will exit the loop only when the user enter n or N
You did not initialize variable yn. So this statement
while(yn != 'y' || yn != 'Y' || yn != 'n' || yn != 'N')
has no sense and in fact it is unnecessary.
Try the following code
#include <iostream>
int main()
{
char yes_no;
do
{
std::cout << "\nHello world!" << std::endl;
std::cout<< "Do you want to repeat? (enter Y/N): ";
std::cin >> yes_no;
} while ( yes_no == 'y' || yes_no == 'Y' );
}
Thank you all for help. I have got what i wanted from all of you. Here is the final code running successfully. I have improved my code using suggestion from everyone of yours opinion.
int main()
{
char yes,yn;
do
{
.......... (main content of program, do things here.)
do
{
cout<<"Do again? (Y/N):";
cin>>yes;
yn = toupper(yes);
if(yn!='N' && yn != 'Y')
{
cout<<"Invalid selection"<<endl;
}
if(yn=='N' || yn == 'Y')
{
break;
}
}
while(true);
}
while(yn == 'Y');
}

Storing locations in Array as a variable to be changed in a if statement

Is there a way to store the x and y entered by the user into a location for the array.
I have this:
if (x == 1 && y == 1)
{
board[0][0] = playerMarker;
}
I want to make it so the x and y are stored into a variable that matches the name of a spot in an array.
But I want to try and make it more like this:
if (currentMove == '1' && squareOne == '1')
squareOne = playerMarker;
This is a code I have seen above. The code bellow is my own.
void playerMove(char* CurrentPlayer, char (&board)[3][3], char &playerMarker)
{
bool bValidMove;
int x,y;
// Prompt the player for a move
cout << "Player " << CurrentPlayer << "'s move:" << endl;
// Loop until we get a valid move
do
{
cout << "Please enter the row number for the place you wish to mark: " << endl;
cin >> x;
cout << "Please enter the column number for the place you wish to mark" << endl;
cin >> y;
bValidMove = true;
// Check for a valid move
if (x == 1 && y == 1)
{
board[0][0] = playerMarker;
}
else if (x == 1 && y == 2)
{
board[0][1] = playerMarker;
}
else if (x == 1 && y == 3)
{
board[0][2] = playerMarker;
}
else if (x == 2 && y == 1)
{
board[1][0] = playerMarker;
}
else if (x == 2 && y == 2)
{
board[1][1] = playerMarker;
}
else if (x == 2 && y == 3)
{
board[1][2] = playerMarker;
}
else if (x == 3 && y == 1)
{
board[2][0] = playerMarker;
}
else if (x == 3 && y == 2)
{
board[2][1] = playerMarker;
}
else if (x == 3 && y == 3)
{
board[2][2] = playerMarker;
}
else
{
cout << "Invalid Move. Try again." << endl;
bValidMove = false;
}
}
while (!bValidMove);
}
This is the code I am trying to make my own into.
// Ask current player for a move
cout << currentPlayer << "'s move: ";
bool validMove;
// Loop until a valid move is chosen
do
{
char currentMove;
cin >> currentMove;
validMove = true;
// Check for a valid move
if (currentMove == '1' && squareOne == '1')
squareOne = playerMarker;
else if (currentMove == '2' && squareTwo == '2')
squareTwo = playerMarker;
else if (currentMove == '3' && squareThree == '3')
squareThree = playerMarker;
else if (currentMove == '4' && squareFour == '4')
squareFour = playerMarker;
else if (currentMove == '5' && squareFive == '5')
squareFive = playerMarker;
else if (currentMove == '6' && squareSix == '6')
squareSix = playerMarker;
else if (currentMove == '7' && squareSeven == '7')
squareSeven = playerMarker;
else if (currentMove == '8' && squareEight == '8')
squareEight = playerMarker;
else if (currentMove == '9' && squareNine == '9')
squareNine = playerMarker;
else
{
cout << "Invalid Move. Try again: ";
validMove = false;
}
} while ( !validMove );
ok this is just a guess at what you want, but here it goes:
do
{
cout << "Please enter the row number for the place you wish to mark: " << endl;
cin >> x;
cout << "Please enter the column number for the place you wish to mark" << endl;
cin >> y;
bValidMove = true;
int xx = x-'1';
int yy = y-'1';
if ( xx < 0 || xx > 2 || yy < 0 || yy > 2 )
{
cout << "Invalid Move (outside board). Try again: ";
validMove = false;
} else if ( board[xx][yy] == 0 ) {
board[xx][yy] = playerMarker;
} else {
cout << "Invalid Move (position already taken). Try again: ";
validMove = false;
}
etc etc
This assumes the board is a 3x3 array, containing 0 when the position is not taken by a player, and takes row 1/2/3 and col 1/2/3 as input.
Hope this helps...
You could do
char& squareOne = board[0][0];
char& squareTwo = board[0][1];
char& squareThree = board[0][2];
char& squareFour = board[1][0];
...
The ampersand(&) means that squareFour is a reference to board[1][0] (they share the same underlying memory, so changing one is changing both).
Note that instead of 9 'if's, you can compute the row/column and set
board[row][column] = playerMarker (row & column may be reversed for you)