I'm working on something along the lines of a console based Tamagotchi (I can't draw, so I'm working with what I've got). For my menu functions, I'm trying to present a menu > take in user input as a char > convert the char to an int > perform selection.
#include <iostream>
//Functions
void menuShow();
int menuChoice();
void menuAction();
int main()
{
menuAction();
}
//Menu display
void menuShow()
{
std::cout << "\nPlease choose from the following:" << std::endl;
std::cout << "(S)tatus of your pet." << std::endl;
std::cout << "(F)eed your pet." << std::endl;
std::cout << "(Q)uit." << std::endl;
}
//Convert input from char to int
int menuChoice()
{
char userChoice;
int convertChoice = 0;
do
{
menuShow();
std::cout << "Choice: ";
std::cin >> userChoice;
if ((userChoice = 'S') || (userChoice = 's'))
{
convertChoice = 1;
}
else if ((userChoice = 'F') || (userChoice = 'f'))
{
convertChoice = 2;
}
else if ((userChoice = 'Q') || (userChoice = 'q'))
{
convertChoice = 3;
}
} while ((userChoice != 'S') || (userChoice != 's') || (userChoice != 'F') || (userChoice != 'f') || (userChoice != 'Q') || (userChoice != 'q')); //Repeat if incorrect selection is made
return convertChoice; //return converted int
}
//Get converted choice and perform related action
void menuAction()
{
int choice;
do
{
choice = menuChoice(); //initialize using returned convertChoice
switch (choice)
{
case 1:
std::cout << "You look at your pets' stats" << std::endl;
break;
case 2:
std::cout << "You feed your pet" << std::endl;
break;
default:
std::cout << "You have quit!" << std::endl;
break;
}
} while (choice != 3);
}
As of right now it doesn't accept an input and perform the action, it just spits out the menu over and over. So my questions are: 1) Am I on the right track for this conversion to work or am I not even close? 2) If I'm way off, can you push me in the right direction (given that this is possible)?
Also, I know this could be taken care of by using int's for the user selections and passed to the switch. However, I wanted to see if I could do this for future reference, as well as try to think "outside the box" in terms of the repetitive "option 1:", option 2:", etc.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The area that I think needs work is the do while loop because I want it to loop when it only ties. However it also loops when the user wins or loses.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROCK = 1;
const int PAPER = 2;
const int SCISSORS = 3;
int getComputerChoice();
int getUserChoice();
void displayChoice(int);
int winner(int, int);
MAIN FUNCTION
int main()
{
int computerChoice,
userChoice;
int playAgain;
THE DO WHILE LOOP DOES WORK BUT IF I WIN OR LOSE IT STILL LOOPS. I JUST WANT IT TO LOOP IF A TIE OCCURS.
do
{
computerChoice = getComputerChoice();
userChoice = getUserChoice();
displayChoice(computerChoice);
playAgain = winner(computerChoice, userChoice);
} while (playAgain == 1);
return (0);
}
THIS GETS THE COMPUTER CHOICE
int getComputerChoice()
{
unsigned seed = time(0);
srand(seed);
return (rand() % (SCISSORS - ROCK + 1)) + ROCK;
}
THIS IS GOOD I THINK
int getUserChoice()
{
int uChoice;
cout << "Enter your choice of Rock, Paper, Scissors.\n"
<< "(1) For rock, (2) for paper, (3) for scissors: ";
cin >> uChoice;
while (uChoice < 1 || uChoice > 3)
{
cout << "Please enter a number between 1 and 3. Try again, thank you.";
uChoice = getUserChoice();
}
return uChoice;
}
THIS IS GOOD I THINK.
void displayChoice(int computerChoice)
{
cout << "Computer Choice: ";
if (computerChoice == 1)
cout << ROCK;
else if (computerChoice == 2)
cout << PAPER;
else if (computerChoice == 3)
cout << SCISSORS;
cout << endl;
}
AREA I THINK NEEDS WORK.
int winner(int computerChoice, int userChoice)
{
int playAgain = 1;
if (computerChoice == ROCK)
{
if (userChoice == SCISSORS)
{
cout << " You lose :( (The Rock smashes the Scissors) ";
}
else if (userChoice == PAPER)
{
cout << "You win! (Paper beats rock) ";
}
else if (userChoice == ROCK)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == PAPER)
{
if (userChoice == ROCK)
{
cout << "You lose :( (Paper wraps rock)";
}
else if (userChoice == SCISSORS)
{
cout << "You win! (Scissors cuts paper)";
}
else if (userChoice == PAPER)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == SCISSORS)
{
if (userChoice == ROCK)
{
cout << "You Win! (The rock smashes the scissors.)";
}
else if (userChoice == PAPER)
{
cout << "You lose :(. (Scissors cuts paper.)";
}
else if (userChoice == SCISSORS)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
cout << endl;
return playAgain;
}
Within winner, you attempt to update playAgain with playAgain == 0. But == is the equality operator. It does not perform assignment. The assignment operator is =, i.e. a single equal sign. As a result, playAgain is never updated, and winner() always returns 1.
To fix, use the assignment operator instead of the equality operator when updating a variable's value.
I found an RPS game and wanted to improve on it by creating a scoring system but the //int compwin = compwin + 1; keeps giving me errors. I am still fairly new to coding in C++ and have no clue where the problem is standing so thanks for helping in advance. Also this code was taken from somewhere this is not my code but I wanted to try and improve on it.
#include <iostream>
#include <cstdlib>
#include <limits>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int choice;
int i;
int y;
int Y;
int comp;
char res;
int compwin = 0;
int choicewin = 0;
unsigned seed;
while (1==1) {
//The choices
cout << "Game Choices.\n\n";
cout << "1.Rock\n";
cout << "2.Paper\n";
cout << "3.Scissors\n";
cout << "4.Quit, exits the game.\n\n";
cout << "Please enter your choice.\n\n";
cin >> choice;
//-----------------------Player Imputs-----------------------------------
if (choice == 1) //Rock
{
cout << "You picked Rock.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 2) //Paper
{
cout << "You picked Paper.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 3) //Scissors
{
cout << "You picked Scissors.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 4)
{
return 0;
}
else if (choice != 1 || 2 || 3 || 4) // Debug
{
cout << "Uhhhh thats not one of the following.\n\nGoodbye!\n\n";
system("pause");
return 0;
}
//-------------------------Computer Choice-------------------------------
seed = time(0);
srand(seed); //RNG TIME
comp = rand() % 3 + 1; //Computer picks
if (comp == 1) //Computer rock
{
res = 1;
cout << "Rock!\n\n";
}
else if (comp == 2) //Computer paper
{
res = 2;
cout << "Paper!\n\n";
}
else if (comp == 3) // Computer scissors
{
res = 3;
cout << "Scissors!\n\n";
}
//-----------------------Victory Conditions------------------------------
if (comp == 1 && choice == 1) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 1 && choice == 3) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 2) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 1) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 3) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 2) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else {
std::cout << "Congrats! You won!" << endl;
//int choicewin = choicewin + 1; This is where the problem occurs
}
cout << "Heres the score, computer =" << compwin << "and player =" << choicewin;
cout << "Want to go again? (y/n)";
cin >> res;
system("cls");
}
while (res == y || Y);
system("pause");
return 0;
}
This
int compwin = compwin + 1;
is a declaration and initialization. A rather weird one, and to discuss why it is allowed would take us on a too big detour. So lets look at a simpler example:
int compwin = 1; // declares compwin and initializes it with 1
int compwin = 2; // compiler error, because compwin is already declared
You can only declare the same variable once (again the long complete truth is more involved, search for "shadowing" in case you care). You also only need to initialize a variable only once.
If you want to assign something to an already declared variable, you use assignment, as in
int compwin = 1; // declare and initialize
compwin = 2; // assign
Further note that
else if (choice != 1 || 2 || 3 || 4) // Debug
is not doing what you expect. The correct way is
else if (choice != 1 && choice != 2 && choice != 3 && choice != 4)
The mistake is a combination of ignoring De Morgan's Law and a wrong combination of several conditions. The operator|| expects a bool on both sides and unfortunately numbers happily convert to true (only 0 becomes false), but a good compiler may spit out warnings on that. Similar mistake is on while (res == y || Y);.
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 6 years ago.
Improve this question
here is my main . I get the error for the part I am checking whether the game had a winner or not. the errors are referring to the if parts where i wanna check the returned data from chkwin method
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
int main()
{
string choice = "";
string name1 = "";
string name2 = "";
string change = "";
int choice_num;
TicTacToe game;
cout << "Welcome to TicTacToe World!\n"
<< "In order to Start Please Enter the name of the first player\n\n";
getline(cin, name1);
cout << "\nGreat, Now Please Enter the name of the second player\n\n";
getline(cin,
name2);
cout << "\nAwesome Let's Get Started!\n";
do
{
cout << "\nPlease choose what do you want to do by entering the number of your choice\n"
<< "1.Start the game.\n"
<< "2.Change the names.\n"
<< "3.View Scores\n"
<< "4.Exit the Game :(\n\n";
getline(cin, choice);
if (choice == "1")
{
for (int i = 1; 1 <= 9; i++)
{
if (i % 2 != 0)
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice_num;
cin.ignore();
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
}
else
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice;
cin.ignore();
game.setMove(choice_num, 2);
if ( 1 == game.chkWin)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout << "The Game is a Draw! ";
}
}
}
}
else if (choice == "2")
{
do
{
cout << "\nwhich player do you want its name to be changed? (Enter 1 for the first, 2 for the second and 3 for both)\n";
getline(cin, change);
if (change == "1")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
}
else if (change == "2")
{
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else if (change == "3")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else
{
cout << "\nPlease Enter a Valid Choice.\n";
}
} while (change != "1" && change != "2" && change != "3");
}
else if (choice == "3")
{
cout << "\n" << game.getResults(name1, name2);
}
else if (choice != "4")
{
cout << "\nPlease Enter a Correct number\n";
}
} while (choice!= "4");
cout << "\nFinal Results are: \n\n"
<< game.getResults(name1, name2);
cout << "\nThank you for using our program. Hope to see You Again. Bye Bye!!\n";
system("Pause");
return 0;
}
my class
#include<iostream>
#include<string>
using namespace std;
#ifndef TICTACTOE_H
#define TICTACTOE_H
class TicTacToe
{
private:
const static int SIZE = 3;
int table[SIZE][SIZE];
int results[SIZE];
int winner = 2;
public:
TicTacToe();
void setMove(int , int );
int chkWin();
string getResults(string , string );
};
#endif
here is my methods declaration:
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
TicTacToe::TicTacToe()
{
for (int i = 0; i < SIZE; i++)
{
results[i] = 0;
for (int j = 0; j < SIZE; j++)
{
table[i][j] = 0;
}
}
}
void TicTacToe::setMove(int place, int player)
{
int field = place;
if (field == 1)
{
if (table[0][0] == 0)
{
table[0][0] = player;
}
else
{
cout << "\nYou cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 2)
{
if (table[0][1] == 0)
{
table[0][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 3)
{
if (table[0][2] == 0)
{
table[0][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 4)
{
if (table[1][0] == 0)
{
table[1][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 5)
{
if (table[1][1] == 0)
{
table[1][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 6)
{
if (table[1][2] == 0)
{
table[1][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 7)
{
if (table[2][0] == 0)
{
table[2][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 8)
{
if (table[2][1] == 0)
{
table[2][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 9)
{
if (table[2][2] == 0)
{
table[2][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
}
int TicTacToe::chkWin()
{
for (int i = 0; i < SIZE; i++)
{
if (table[i][0] == table[i][1] && table[i][0] == table[i][2])
{
if (table[i][0] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[i][0] == 2)
{
results[2] += 1;
winner = -1;
}
}
else if (table[0][i] == table[1][i] && table[0][i] == table[2][i])
{
if (table[0][i] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[0][i] == 2)
{
results[2] += 1;
winner = -1;
}
}
}
if ((table[0][0] == table[1][1] && table[0][0] == table[2][2]) || (table[0][2] == table[1][1] && table[0][2] == table[2][0]))
{
if (table[1][1] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[1][1] == 2)
{
results[2] += 1;
winner = -1;
}
}
else
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if(table[i][j] == 0)
{
winner = 2;
}
}
}
results[1] += 1;;
return winner;
}
}
string TicTacToe::getResults(string name1, string name2)
{
return ( name1 + " : " + to_string(results[0]) + "\n"
+ "Draws : " + to_string(results[1]) + "\n"
+ name2 + " : " + to_string(results[2]) + "\n");
}
Compareing functions with integers doesn't make sense. You have to use () operator to call functions like this:
if (game.chkWin() == 1)
instead of
if (game.chkWin == 1)
Poor:
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
Better:
game.setMove(choice_num, 1);
switch (game.chkWin()) {
case 1:
cout << name1 << " has won this Game!";
break;
case -1:
cout << name1 << " has won this Game!";
break;
case 0:
cout <<"The Game is a Draw! ";
break;
}
The basic problem is using "==" with function game.chkWin, instead of with the result of function game.chkWin().
But in cases like this (pun intended) a "switch()" block is probably more readable and better style than multiple "if/else" statements.
'Hope that helps...
I am capturing video from my webcam and if the user hits the Enter key I take a picture. Then I ask "Is the picture okay?" to user and wait for an input. If he says "No", I keep doing the same thing, until he says "Yes".
But if he says "No", and in the meantime I type something in the terminal, getline() function writes whatever I type into its buffer, and when I ask the question again it goes directly to "invalid input" state.
How do I prevent this?
I have read a lot of questions regarding this and I tried to use cin.ignore() and cin.clear() before/after after I call getline(), but they didn't help.
// Do capturing here
string choice;
int choiceIsOkay = 0;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "\nInvalid input\n";
choiceIsOkay = 0;
}
}
if (choiceIsOkay == 2)
{
runAlgorithm = 1;
break;
}
else choiceIsOkay = 0;
If I understand your issue, if user enters Some Random Text In, your program always jump in "Invalid input" and never stops to wait for users input. Following code should resolve your issue.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int runAlgorithm;
// Do capturing here
int i = 0;
while (i++ < 3)
{
int choiceIsOkay = 0;
string choice;
while (choiceIsOkay == 0)
{
cout << "Is the picture okay? (Y/N): ";
getline(cin, choice);
if ((choice == "Y") || (choice == "y"))
{
choiceIsOkay = 2;
}
else if ((choice == "N") || (choice == "n"))
{
choiceIsOkay = 1;
}
else
{
cout << "nInvalid inputn";
choiceIsOkay = 0;
}
// Ignore to the end of line
cin.clear();
}
}
return 0;
}
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
}