hey guys so this is my program, I need to notify the user that if hhe/she enters a letter other than w d b or w that is an invalid request. what ive done so far does this, but when i input a number to the dollars_withdraw or dollars_deposit or account_balance the program will do the transaction but also add the "invalid request" before going back to main loop. how do i change it so the program wont do that for numerical inputs for the withdraw deposit and balance?:
// Atm machine.cpp : Defines the entry point for the console application.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char user_request;
string user_string;
double account_balance, dollars_withdraw, dollars_deposit;
account_balance = 5000;
while(account_balance >0)
{
cout << "Would you like to [W]ithdraw, [D]eposit, Check your [b]alance or [Q]uit?"
<< endl;
cin >> user_string;
user_request= user_string[0];
if(user_request == 'w' || user_request== 'W')
{
cout << "How much would you like to withdraw?" << endl;
cin >> dollars_withdraw;
if (dollars_withdraw > account_balance || dollars_withdraw <0)
cout << "Invalid transaction" << endl;
else
account_balance = account_balance - dollars_withdraw;
cout << "Your new balance is $" << account_balance << endl;
}
if (user_request == 'd' || user_request== 'D')
{
cout << "How much would you like to deposit?" << endl;
cin >> dollars_deposit;
if (dollars_deposit <0)
cout << "Invalid transaction" << endl;
else
account_balance= account_balance + dollars_deposit;
cout << "Your new balance is $" << account_balance << endl;
}
if(user_request == 'b' || user_request == 'B')
{
account_balance= account_balance;
cout << "Your available balance is $" << account_balance << endl;
}
if(user_request == 'q' || user_request == 'Q')
break;
else
cout << "Invalid request " << endl;
}
cout << "Goodbye" << endl;
return 0;
}
Sure it does. Your code says:
If it is a 'w' do something
...
If it is a 'q' do something, else yell "invalid"
So if the user does not enter a 'q', the last 'else' block will always be executed. Either use else if throughout or change your code to use a switch statement:
// Either:
if (user_request == ...) {
...
} else if (user_request == ...) {
...
} else {
std::cout << "invalid";
}
// Or (better, faster):
switch (user_request) {
case 'q':
case 'Q':
...
break;
...
default:
std::cout << "Invalid request";
}
A third option would be to use continue:
while (...) {
user_request = ...
if (user_request == 'w' ...) {
...
continue; // In this iteration, no other code within the while loop is executed.
}
if (...)
...
}
This is a bad programming practice. Please use Switch Case for what you need to achieve. And put a "break" statement after every case branch.
chain your if statements into if, else-if, else-if, ..., else.
else statements only "know of" the if statement immediately previous. For example:
if (myNumber == 0)
{
// Triggers when myNumber is zero.
}
if (myNumber == 1)
{
// Triggers when myNumber is one.
}
else
{
// Triggers when myNumber is not one.
}
This can be fixed with else if statements. In your case it would look something like this:
if (user_request == w)
{
// ...
}
else if (user_request == d)
{
// ...
}
// ...
else cout << "Invalid request.";
In my old CS class, I'd do things like this:
string user_string;
do {
if(user_string) cout << "Enter a valid value!" << endl;
cin >> user_string;
} while(user_string != "w" && user_string != "d");
You need to use else if as follows:
if(user_request == 'w' || user_request== 'W')
{
...
} else if(user_request == 'd' || user_request== 'D')
{
....
} else if(user_request == 'b' || user_request== 'B')
{
.....
} else if(user_request == 'q' || user_request== 'Q')
{
...
} else
{
// Invalid request
}
Related
I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.
I have a class EverTrueHelper.cpp.
bool EverTrueHelper::getAndReturnUserEntry(string userEntry)
{
if (userEntry == "Q" || userEntry == "q")
{
return true;
}
else
{
return false;
}
return 0;
}
and I have these lines of code in my main function
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry = true)
{
break;
}
else
{
continue;
}
I have an error on the "getAndReturnUserEntry" in my if statement. I can't quite figure out how to get around it.
You can call a method by using parentheses (()) and passing the argument(s) in them:
cin >> userEntry;
if (getAndReturnUserEntry(userEntry))
{
break;
}
else
{
continue;
}
You can try like follow:
cin >> userEntry;
EverTrueHelper my_helper;
if (my_helper.getAndReturnUserEntry(userEntry)) {
break;
}else{
continue;
}
You have two problem with your main function's if statement:
A single =, which means assignment, which is invalid in that case.
You have not invoked getAndReturnUserEntry, add () at the end to actually invoke the function. After that, a test for == true is not necessary either since it will work anyway.
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry())
{
break;
}
// continue program...
Further more, I think a better quit checking function will be:
bool EverTrueHelper::getAndReturnUserEntry(string userEntry)
{
return (userEntry == "Q" || userEntry == "q");
}
bool EverTrueHelper::getAndReturnUserEntry(string userEntry) {
return ((userEntry == "Q" || userEntry == "q") ? true : false);
}
cout << "Do you want to quit? Type 'Q' or 'q' else hit Enter" << endl;
cin >> userEntry;
if (getAndReturnUserEntry(userEntry) == true)
; // break; doesn't make sense here
else
; // continue; doesn't make sense here
So i'm making a text adventure game and I want to be able to have a function which has all the inputs in it. So instead of every time me making an if statement to check for every direction I can just put a function that has all of that in it. How do I make this?
string input;
while (input != "n", "s", "e", "w")
{
getline(cin, input);
if (input == "n")
{
dTable();
}
if (input == "e")
{
cout << "You sit on the sofa. Congratulations" << endl;
}
if (input == "w")
{
cout << "You just ran into a wall" << endl;
}
if (input == "s")
{
outsideHouse();
}
if (input == "stats")
{
stats();
}
if (input == "help")
{
help();
}
else
{
cout << "Sorry I am not Siri I don't understand" << endl;
getline(cin, input);
}
break;
}
return 0;
}
You see different approaches of using functions in here,
thats how I would solve this.
You can focus on adding new questions in the main() part and doesn't have to write
all the if-requests over and over.
#include <iostream>
#include <string>
using namespace std;
void help();
void stats();
string check(string input,string n,string s, string w, string e)
{
string result;
if (input == "n"){
result = n;}
else if (input == "s"){
result = s;}
else if (input == "w"){
result = w;}
else if (input == "e"){
result = e;}
else if (input == "help"){
cout << "help" << endl;} //help()
else if (input == "stats"){
cout << "stats" << endl;} // stats()
else if (input == "exit"){
result = "exit";}
else
cout << "Sorry I am not Siri I don't understand. Try again" << endl;
return result;
}
string call()
{
string input;
cout << "Where do you want to go? n s w e" << endl;
getline(cin, input);
return input;
}
int main()
{
bool slope = false;
string input, result;
input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");
while (slope != true)
{
if(result == "house")//room1
{
cout << "You are in the house" << endl;
input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");
}
else if(result == "outside")//room2
{
cout << "You are outside"<< endl;
input = call();
result = check(input,"You just ran into a wall", "house","dTable", "You sit on the sofa. Congratulations");
}
else if(result == "dTable")//room3
{
cout << "You are dTable" << endl;
input = call();
result = check(input,"You just ran into a wall", "You sit on the sofa. Congratulations","outside","house");
} ///adding one room after another and connect it with each other
else if(result == "exit")
{
slope = true;
}
else
{
cout << result << endl;
input = call();
//some winning or loosing message here
}
}
return 0;
}
I'm nearly finished working on a small guessing game, but i have run into a problem I don't know how to work around.
The problem is with the check_guess function that is checking to make sure the guess being input is a number between 1 and 100.
When running the program the first time, everything works fine.
http://i.imgur.com/pprunDT.png (I would post images if my reputation weren't so low)
But every time after, where yes to play again is chosen, the program runs through the check_guess function and displays "Invalid Input" when it shouldn't
http://i.imgur.com/8OSnSJt.png
I'm not sure why the program is behaving this way.
The code for the entire program is here:
#include <iostream>
#include <cstdlib> //for rand
#include <ctime> //for time
#include <string>
#include <sstream> //for conversions from string to int
using namespace std;
int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
cin >> yn;
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
int main()
{
srand(time(0)); //sets seed to be random
int mystery = 0; //defines mystery number
int guess = 0; //defines guess
int tries = 5; //defines trys
bool quit = false; //defines replay or quit
cout << "----------------------------------\n";
do { //while mode is not set to quit, keep playing
tries = 5; //resets tries each new game
mystery = rand() % 100 + 1; //sets mystery number to be random
guess = 0;
cout << "Pick a number between 1 and 100.\n\nYou have 5 tries: ";
while (tries != 0) { //loops until you have no tries left
guess = check_guess(tries);
if (guess == mystery) { tries = 0; } //if you guess right it ends the loop
else { tries--; } //guessing wrong lowers tries by 1
if ( tries != 0 && guess > mystery) {
cout << guess << " is too high.\n" << endl;
cout << "You have " << tries << " tries: ";
}
if ( tries != 0 && guess < mystery) {
cout << guess << " is too low.\n" << endl;
cout << "You have " << tries << " tries: ";
}
}
if (guess == mystery) { //if guess == mystery by time loop ends you win
cout << "Got it! You Win!\n" << endl;
}
else { //if not, you lose
cout << "You Lose! The number was: " << mystery << ".\n" <<endl;
}
cout << "-------------------\n";
cout << "Play Again?(y/n): "; //ask user to play again
quit = play_again();
cout << "-------------------\n";
if (quit == false)
cout << endl;
} while (quit == false);
cout << "----------------------------------" << endl;
return 0;
}
I'm not sure how to fix this.
this line:
cin >> yn;
only reads the 'y' but not the end of line. As a result, the next execution of this instruction
getline (cin, guess);
initializes guess to an empty string.
On line 19, import the code "cin.ignore();" without quotations.
So your code reads as
`int check_guess(int tries) { //function for limiting the input of guess
string guess = "";
int result = 0;
do {
getline (cin, guess);
istringstream convert(guess);
if ( !(convert >> result) || (result < 1 || result > 100) ) {
result = 0;
cin.ignore();
cout << "Invalid Input.\n" << endl;
cout << "You have " << tries << " tries: ";
}
} while (result == 0);
return result;
}
`
and so on. This stops input into the console briefly. You're code is reading the 'y' to try again as the input for the number when you restart as well. Putting in the little line cin.ignore(), stops it from inputting y twice.
Change play_again() to:
bool play_again() { //function for limiting the input of mode
bool quit;
string yn;
do {
getline (cin, yn);
if ( yn == "y" || yn == "yes" ) {
quit = false;
}
else if ( yn == "n" || yn == "no" ) {
quit = true;
}
else {
yn = "invalid";
cout << "Invalid input.\n\nEnter 'y' or 'n': ";
}
} while ( yn == "invalid" );
return quit;
}
Ok I have a problem here. I am making a slide puzzle game. The player is asked which piece he wants to move until the puzzle is solved. If the player wants to exit before, typing Q or q and pressing enter will do it. The program works just fine. BUT I am having one problem: if I insert CTRL+Z, the program will loop unexpectedly...
This is the piece of code that matters:
// analyzes user input
if (piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
pressanykey();
break;
}
else
{
piece_to_move = atoi(piece_to_move_string.c_str());
if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
{
game_board = move_piece (game_board, piece_to_move);
}
else
{
cout << "Not possible.";
}
}
EDIT: but still doesn't work..
// analyzes user input
if (piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
pressanykey();
break;
}
else if (cin.eof())
{
//do nothing
}
else
{
piece_to_move = atoi(piece_to_move_string.c_str());
if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
{
game_board = move_piece (game_board, piece_to_move);
}
else
{
cout << "Not possible.";
}
}
Ctrl+Z means "end of file" (assuming you're on Windows) so once the user hits that, your cin is in an unreadable state. Check for cin.eof():
if (cin.eof() || piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
}