Converting Integers to Strings and If.. Else Boolean Functions C++ - c++

I am working on this assignment that requires me to create a game of rock, paper scissors for my programming class. I have ran into a couple issues that I am not fully educated about as I am still learning the basics of this language. My professor wants me to take in the users choice and the computers choice and then change it from an int to a string and print it out as "You chose: Rock" instead of "You chose: 1" which is what it is doing now. This part would be in the getComputerChoice() and getPlayerChoice() functions. Another issue I am having trouble with is my professor wants us to check if it was a tie or if the player won and I am trying to put these functions in an If else statement but I am not exactly sure what the proper way to declare the function in the else statement is. (This is commented out in the else part of the if statement in main all the way at the bottom)
My code is as follows:
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int getComputerChoice();
int getPlayerChoice();
bool isTie(int, int);
bool isPlayerWinner(int, int);
int getComputerChoice()
{
int comp;
string cpChoice;
comp = rand() % 3 + 1;
if (comp == 1)
{
cpChoice = "Rock";
}
else if (comp == 2)
{
cpChoice = "Paper";
}
else if (comp == 3)
{
cpChoice = "Scissors";
}
return comp;
}
int getPlayerChoice()
{
int userChoice;
string strChoice;
cout << "Rock, Paper, or Scissors?\n";
cout << "1) Rock\n";
cout << "2) Paper\n";
cout << "3) Scissors\n";
cout << "Please enter your choice : \n";
cin >> userChoice;
cout << '\n';
while(userChoice < 1 || userChoice > 3)
{
cout << "Invalid Selection\n";
cout << "Re-enter a number between 1 and 3\n";
cin >> userChoice;
}
if (userChoice == 1)
{
strChoice = "Rock";
}
else if (userChoice == 2)
{
strChoice = "Paper";
}
else if (userChoice == 3)
{
strChoice = "Scissors";
}
return userChoice;
}
bool isTie(string userChoice, string comp)
{
if (userChoice != comp)
return false;
else
return true;
}
bool isPlayerWinner(int userChoice, int comp)
{
if ((comp == 1 && userChoice == 2) || (comp == 3 && userChoice == 1) || (comp == 2 && userChoice == 3))
return true;
else
return false;
}
int main()
{
char selection;
int computerChoice;
int userChoice1;
string Rock;
string Paper;
string Scissors;
srand ((unsigned int)time(NULL));
do
{
cout << '\n';
cout << "ROCK PAPER SCISSORS MENU\n";
cout << "-------------------------\n";
cout << "p) Play Game\n";
cout << "q) Quit\n";
cout << "Please enter your choice : \n";
cin >> selection;
cout << '\n';
cout << '\n';
// cin >> selection;
if (selection == 'p' || selection == 'P')
{
computerChoice = getComputerChoice();
//string computerChoice = to_string(comp);
userChoice1 = getPlayerChoice();
//string userChoice1 = to_string(userChoice);
cout << "You chose: " << userChoice1 << '\n';
cout << "The computer chose: " << computerChoice << '\n';
if (isTie(computerChoice, userChoice1)== true)
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "It's a TIE!";
}
else //(isPlayerWinner(computerChoice, userChoice1));
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "You WIN!";
}
}
//else if (selection != 'p' || selection != 'q')
//{
// cout << "Invalid Selection. Try Again.\n";
// cout << '\n';
// cin >> selection;
//}
else if (selection == 'q' || selection == 'Q')
{
cout << "You have chosen to quit the program. Thank you for using the program!\n";
}
else if (selection != 'p' || selection != 'q')
{
cout << "Invalid Selection. Try Again.\n";
cout << '\n';
}
}while (selection != 'q');
}
ANOTHER NOTE: my professor doesn't want any void functions and doesn't want any global variables.
She told me that my isTie function was fine but didn't mention anything about the isPlayerWinner function. I believe it is fine and has no issues, I am just not sure how to declare it in the main if else statement. Any help would be appreciated and if you guys have any questions or need more info please let me know. Thanks in advance.

You pretty much have everything right.
Your getPlayerChoice() and getComputerChoice() functions right now are both returning an int that stand for the players choice. You calculate the name for that choice in those functions, but dont do anything with the actual string representing the choice. You either need to return the choice string, or make a function that takes in an int and returns name associated with that choice:
string getChoiceName(int choice)
{
string strChoice;
if (choice== 1)
{
strChoice = "Rock";
}
else if (choice== 2)
{
strChoice = "Paper";
}
else if (choice== 3)
{
strChoice = "Scissors";
}
return strChoice;
}
I prefer the method, as it make it easier to calculate the result of the match if you have the ints. There are a lot of other routes you could take, like making an enum representing choices - even the function I gave you here isn't great, but it should get you to a working state.

Related

Why does my program terminate when it should continue?

#include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
cout << "What question would you like to ask the Magic 8 ball?: \n";
cout << "\n";
cin >> question;
answer = rand () % 8 + 1;
if (answer == 1) {
cout << "The answer is: It is certain\n";
} else if (answer == 2) {
cout << "The answer is: It is decidely so\n";
} else if (answer == 3) {
cout << "The answer is: Most likely\n";
} else if (answer == 4) {
cout << "The answer is: Signs point to yes\n";
} else if (answer == 5) {
cout << "The answer is: Ask again later\n";
} else if (answer == 6) {
cout << "The answer is: Don't count on it\n";
} else if (answer == 7) {
cout << "The answer is: My sources say no\n";
} else {
cout << "The answer is: Reply hazy, try again\n";
}
cout << "Would you like to play again?(y/n): ";
cin >> play;
if (play == "yes" || play == "y") {
cin >> question;
} else if (play == "no" || play == "n") {
cout << "Thank you for playing with the Magic 8 Ball";
}
return 0;
}
It stops the program after it gives my answer, not letting the user answer if they want to play again or not. Please help me, I've been stuck on this for a while now and don't know what to do.
You have to add
getline(cin, question);
If you don’t,
cin >> question;
won’t be able to read more than one word.
you did most of the work you just have to make a loob like so
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
while(play!="no"&&play!="n")
{
play = "";
cout << "What question would you like to ask the Magic 8 ball?: \n";
cout << "\n";
cin >> question;
answer = rand () % 8 + 1;
if (answer == 1) {
cout << "The answer is: It is certain\n";
} else if (answer == 2) {
cout << "The answer is: It is decidely so\n";
} else if (answer == 3) {
cout << "The answer is: Most likely\n";
} else if (answer == 4) {
cout << "The answer is: Signs point to yes\n";
} else if (answer == 5) {
cout << "The answer is: Ask again later\n";
} else if (answer == 6) {
cout << "The answer is: Don't count on it\n";
} else if (answer == 7) {
cout << "The answer is: My sources say no\n";
} else {
cout << "The answer is: Reply hazy, try again\n";
}
cout << "Would you like to play again?(y/n): ";
while(play != "no" && play != "n"&& play != "y" && play != "yes")
{cin >> play;
if (play == "no" || play == "n") {
cout << "Thank you for playing with the Magic 8 Ball";
} else if (play != "no" && play != "n"&& play != "y" && play != "yes") {
cout<<"you enter an unknown value, try agein"<<endl;
}
}
}
return 0;
}
i declare (string play) then i reassign it so it could not save the y/n answer from round to round cuz that would break the program and i add a loob down the code that will get you y/n answer more effective

How to add a text file to a game so that it can track a person's score

I have written a code that displays a rock-paper-scissors game against the computer. I would like to add a feature where I can create a text file in order to store the person's score and the computer score and keep track of the score but I don't know how to do it. Thank you in advance!
Here is my code.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void rock_paper_scissors()
{
static int userscore = 0;
static int computerscore = 0;
string playername;
int userchoice;
int computerchoice;
cout << "Hello to rock-paper-scissors!\n";
cout << "rock beats scissors, scissors beats paper and paper beats rock." << endl;
cout << "choose 1 for rock, 2 for paper, 3 for scissors.\n";
cout << "please enter your name." << endl;
cin >> playername;
cout << endl;
cout << "Please enter your choice\n";
cin >> userchoice;
cout << endl;
while (!(userchoice > 0 && userchoice <= 3))
{
cout << "invalid choice. please enter a number between 1 and 3\n";
cin >> userchoice;
}
if (userchoice == 1)
{
cout << playername << " picked rock." << endl;
}
else if (userchoice == 2)
{
cout << playername << " picked paper." << endl;
}
else if (userchoice == 3)
{
cout << playername << " picked scissors." << endl;
}
computerchoice = (rand() % 3) + 1;
if (userchoice == 1 && computerchoice == 3)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == 2 && computerchoice == 1)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == 3 && computerchoice == 2)
{
cout << playername << " wins!" << endl;
}
else if (userchoice == computerchoice)
{
cout << " draw!" << endl;
}
else
{
cout << "computer wins!" << endl;
}
cout << "thank you for playing!\n";
string restart;
cout << "Would you like to play again?" << endl << "(y)es / (n)o" << endl;
cin >> restart;
if (restart == "y")
{
rock_paper_scissors();
}
}
int main()
{
cout << "MAIN\n";
rock_paper_scissors();
return 0;
}
Why do you need to write the data into in file? Updating a simple txt file after each round could be cumbersome, as you always result in a single score at the end of the program. I would suggest changing the type of the rock_paper_scissors into int indicating the score achieved by the player in a single lot. The intermediate results are irrelevant. Just place the game loop into your main function and do not use a recursive function call and static function variables here. Otherwise, the player is forced to enter his name for every single lot.
Moreover, I tested your code and you have to change your error handling. I typed in "rock" and the program stuck in an infinity loop "invalid choice. please enter a number between 1 and 3\n" Whereby it is not possible to make another entry. As I entered a string instead of an integer, you have to reset the console. Beware of the dumbest possible user.
Moreover, you should seed your program to avoid identical computer choices in each game. This could be done with srand(time(NULL)).
Eventually, I write the tracked score into a score file at the end of the main function using the fstream standard library.
#include <iostream>
#include <string>
#include <algorithm> // min max
#include <fstream> // read/write from/to files
#include <time.h> // time
using namespace std;
int rock_paper_scissors(const std::string& playername);
int main()
{
srand(time(NULL));
cout << "MAIN\n";
cout << "Hello to rock-paper-scissors!\n";
cout << "rock beats scissors, scissors beats paper and paper beats rock." << endl;
cout << "choose 1 for rock, 2 for paper, 3 for scissors.\n";
int userscore = 0;
int computerscore = 0;
std::string playername;
std::string restart;
cout << "please enter your name." << endl;
cin >> playername;
cout << endl;
do
{
int result = rock_paper_scissors(playername);
cout << "thank you for playing!\n";
userscore += result;
computerscore += std::max(0, 3 - 2 * result);
cout << playername << "'s score: " << userscore;
cout << "\ncomputer's score: " << computerscore;
cout << "\nWould you like to play again?" << endl << "(y)es / (n)o" << endl;
cin >> restart;
} while (restart == "y");
std::ofstream ofile;
ofile.open("scorefile.txt");
ofile << "Scores:\n" << playername << ": " << userscore;
ofile << "\nComputer: " << computerscore;
ofile.close();
return 0;
}
int rock_paper_scissors(const std::string& playername)
{
int userchoice;
int computerchoice;
cout << endl << endl;
do {
cout << "Please enter your choice\n";
if (std::cin >> userchoice)
{
if (userchoice > 0 && userchoice <= 3)
{
break;
}
else
{
cout << "invalid choice. please enter a number between 1 and 3\n";
continue;
}
}
else if (!cin.bad() && !cin.eof())
{
// a non integer value entered
cerr << "invalid choice. please enter a number between 1 and 3\n";
// Reset error state
cin.clear();
// remove error input
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
} while (true);
if (userchoice == 1)
{
cout << playername << " picked rock." << endl;
}
else if (userchoice == 2)
{
cout << playername << " picked paper." << endl;
}
else if (userchoice == 3)
{
cout << playername << " picked scissors." << endl;
}
computerchoice = (rand() % 3) + 1;
if (userchoice == 1 && computerchoice == 3)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == 2 && computerchoice == 1)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == 3 && computerchoice == 2)
{
cout << playername << " wins!" << endl;
return 3;
}
else if (userchoice == computerchoice)
{
cout << " draw!" << endl;
return 1;
}
else
{
cout << "computer wins!" << endl;
return 0;
}
}

C++ Nested Validation loop

My teacher would like me to put a "nested validation loop around the player's choice. That keeps looping until they enter valid input (1, 2, or 3)." I am having trouble getting anything to work could I get some pointers, please and thank you.
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
// Keaton Graffis 12/28/2015
int main()
{
int seed = time(0);
srand(seed);
char playAgain;
int playerChoice, aiChoice, win = 0, tie = 0, lose = 0;
do
{
cout << "Lets play a game of rock paper scissors.\n";
cout << "Enter a 1 for sccisors a 2 for rock or a 3 for paper: ";
// Generates outcomes of the players choice
cin >> playerChoice;
if (playerChoice == 1)
{
cout << "You picked Rock!\n";
}
else if (playerChoice == 2)
{
cout << "You picked Paper!\n";
}
else if (playerChoice == 3)
{
cout << "You picked Scissors!\n";
}
// gentrate the computers choices
int aiChoice = rand() % 3 + 1;
if (aiChoice == 1)
{
cout << "The computer chose Rock!\n";
}
else if (aiChoice == 2)
{
cout << "The computer chose Paper!\n";
}
else if (aiChoice == 3)
{
cout << "The computer chose Scissors!\n";
}
// Determines wins, ties and loses
if (playerChoice == 1 && aiChoice == 1) {
cout << "Rock meets Rock its a tie!" << endl;
tie++;
}
else if (playerChoice == 1 && aiChoice == 2)
{
cout << "Rock is covered by Paper the computer wins!." << endl;
lose++;
}
else if (playerChoice == 1 && aiChoice == 3)
{
cout << "Rock crushes Scissors you win!" << endl;
win++;
}
else if (playerChoice == 2 && aiChoice == 1)
{
cout << "Paper covers Rock you win!" << endl;
win++;
}
else if (playerChoice == 2 && aiChoice == 2)
{
cout << "Paper meets Paper its a tie!" << endl;
tie++;
}
else if (playerChoice == 2 && aiChoice == 3)
{
cout << "Paper is cut by Scissors the computer wins!" << endl;
lose++;
}
else if (playerChoice == 3 && aiChoice == 1)
{
cout << "Scissors are crushed by Rock computer wins!" << endl;
lose++;
}
else if (playerChoice == 3 && aiChoice == 2)
{
cout << "Scissors cuts Paper you win!" << endl;
win++;
}
else if (playerChoice == 3 && aiChoice == 3)
{
cout << "Scissors meet Scissors its a tie!" << endl;
tie++;
}
// Outputs wins, ties and loses
cout << "Wins: " << win << endl;
cout << "Ties:" << tie << endl;
cout << "Losses:" << lose << endl;
cout << "Would you like to play again? Y/N" << endl;
cin >> playAgain;
system("CLS");
// Allow user to play again
} while (playAgain == 'Y' || playAgain == 'y');
}
You can throw a while loop over the block of code that reads in the input and break from the loop when you receive valid input.
int choice;
bool valid = false;
while(!valid) {
cout << "Enter a 1 for scissors, 2 for rock, 3 for paper" << endl;
cin >> choice;
if(choice == 1 || choice == 2 || choice == 3)
valid = true;
}

How to make input string taken as it is instead of only the first character?

I want to create a menu where there is both letter and number.
I tried to use string but now when user input 20, it will only take the first number, which is 2. How do I make so that when user put 20, it will be seen as 20 instead of 2?
#include <iostream>
using namespace std;
int main ()
{
string choice;
cout << "1. A" << endl;
cout << "2. B" << endl;
cout << "3. C" << endl;
cout << "4. D" << endl;
cout << "Q. Quit" << endl;
do
{
cout << "Please enter your choice: ";
cin >> choice;
if (choice[0] == '1')
{
cout << "1";
} else if (choice[0] == '2')
{
cout << "2";
} else if (choice[0] == '3')
{
cout << "3";
} else if (choice[0] == '4')
{
cout << "4";
} else if (choice[0] == 'q' || choice[0] == 'Q')
{
cout << "q";
} else {
cout << "Please choose one of the menu above. " << endl;
}
} while (choice[0] != 1 && choice[0] != 2 && choice[0] != 3 && choice[0] != 4 && choice[0] != 'q');
return 0;
}
You also can see my code at http://cpp.sh/7ipv
Your code treats 20 as 2 because it sees only the first character of the input.
Try this:
#include <iostream>
using namespace std;
int main ()
{
string choice;
cout << "1. A" << endl;
cout << "2. B" << endl;
cout << "3. C" << endl;
cout << "4. D" << endl;
cout << "Q. Quit" << endl;
do
{
cout << "Please enter your choice: ";
cin >> choice;
if (choice == "1")
{
cout << "1";
} else if (choice == "2")
{
cout << "2";
} else if (choice == "3")
{
cout << "3";
} else if (choice == "4")
{
cout << "4";
} else if (choice == "q" || choice == "Q")
{
cout << "q";
} else {
cout << "Please choose one of the menu above. " << endl;
}
} while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "q" && choice != "Q");
return 0;
}

C++ Troubleshooting my command line calculator

I am using xcode for my c++. It is a simple command line calculator.
This is what I have so far:
//
// main.cpp
// test
//
// Created by Henry Bernard Margulies on 8/21/13.
// Copyright (c) 2013 Henry Bernard Margulies. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
bool loopy = true;
cout << "\nCalculator\n";
while (loopy == true)
{
bool gooy;
double answ; // answer
double fn; // first number
double sn; // second number
string opersym; // operation symbol
string oper; // operation
string more; // rerun the program or not
cout << endl << "Operation please (+, - , x or d): "; //Problem1
cin >> oper;
if (oper == "+") //makes sure operation is viable
{
gooy = true;
}
if (oper == "-")
{
gooy = true;
}
if (oper == "x")
{
gooy = true;
}
if (oper == "d")
{
gooy = true;
} //does the above
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
if (gooy == true)
cout << endl << "First number please: ";
if(!(cin >> fn)) //makes sure it is a number
{
cerr << endl << "Enter a number next time, please try again"; //complaint
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
cout << endl << "Next number: ";
if(!(cin >> sn))
{
cerr << endl << "Enter a number next time, please try again";
gooy = false;
loopy = true;
break; //Problem2
}
if (gooy == true)
{
opersym = oper;
if (oper == "+")
answ = fn + sn;
if (oper == "-")
answ = fn - sn;
if (oper == "x")
answ = fn * sn;
if (oper == "d")
{
opersym = "÷";
answ = fn / sn;
}
cout << endl << "You entered: " << fn << " " << opersym << " " << sn << ". And it equals " << answ;
cout << endl << "Want more? y/n: ";
cin >> more;
if (more == "n")
{
cout << endl << "Okay, I'm not wanted. Shutting down. :(";
return(0);
}
if (more == "y")
{
cout << endl << "Back to work!";
}
else
{
cout << endl << "Since you can not be bothered to type it right, I'll take it as a no. :(";
return(0);
}
}
}
}
return 0;
}
I have several requests:
First, only division seems to work. Check the first part of main where it asks for an operation and confirms it. It does not want to work for +, - or x, but only for d
2.Check the two comments named problem2. In these parts continue; and break; don't restart the calculator properly. I want to go back to the beginning of the while loop and goto is supposedly unstable and bad.
3.Could you correct my code? I am no expert and the whole thing is very dirtily done. Please show me better logic to make the code shorter, faster and more stable.
Thanks!
ps. I'm a 12 year old kid teaching myself c++ off the internet, so please cut me some slack and explain things like you're speaking to a puppy.
Your problem is the else after if (oper == "d") If the operation is not d, the else clause will activate, even if an operation was picked earlier. Try this instead.
if (oper == "+")
{
gooy = true;
}
else if (oper == "-")
{
gooy = true;
}
else if (oper == "x")
{
gooy = true;
}
else if (oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
Now the final else will only activate, if all previous else clauses were activated.
Alternatively
if (oper == "+" || oper == "-" || oper == "x" || oper == "d")
{
gooy = true;
}
else
{
cout << endl << "Enter a real operation"; //complains if oper not viable
gooy = false;
continue;
}
break exits the loop it is in. Try continue instead. It goes back to the top of the loop, and if the condition is true, starts over.
Try to declare variables closer to where they are used. For example answ and opersym are not used until late in the loop. You can declare them local to the if statement block for if (gooy == true)
first of all, good luck with learning C++. I am sure you'll pick it up in no time at all :) Here's a basic calculator. It's not ideal but shorter.
#include <iostream>
#include <string>
int main()
{
using namespace std; //use namespace only within the scope of main()
//ask user to choose operation
string operation = "";//good to initialize local variable. otherwise C++ assigns them garbage values
while(operation != "+" && operation != "-" && operation != "*" && operation != "/")
{
cout << "Please enter a mathematical operation. Options are: + or - or * or /" << endl;
cin >> operation;
}
cout << "You entered " << operation << endl << endl;
//ask user to enter two numbers
double number1 = 0, number2 = 0, result = 0;
bool success = false;//true if calculation carried out successfully
//keep looping till calculation carried out successfully
while(success!=true)
{
cout << "Please enter the first number: " << endl;
cin >> number1;
cout << "Please enter the second number: " << endl;
cin >> number2;
if(operation == "+") result = number1 + number2;
else if(operation == "-") result = number1 - number2;
else if(operation == "*") result = number1*number2;
else if(operation == "/" && number2 != 0) result = number1/number2;
else
{
cout << "Please enter non-zero value for number2 since carrying out division" << endl;
continue;
}
success = true;
cout << "Result is: " << number1 << " " << operation << " " << number2 << " = " << result << endl;
}
return(0);
}