So I'm trying to create a feature that will let me quit my game once you've completed it, or you have the option to play again. The replay option works, but whenever I try the quit part, it just goes back to the start of the game.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
using namespace std;
int main() {
SetConsoleTitle("Guess the number! | v1.0");
int replay;
replay = 1;
int g, n;
play:
g = NULL;
srand(time(NULL));
n = rand() % 20 + 1;
system("cls");
cout << "Number guessing game" << endl;
cout << "********************" << endl;
cout << endl;
cout << "The random number has been generated. It is between 1 and 20" << endl;
system("pause");
while (g != n) {
system("cls");
cout << "Number Guessing Game" << endl;
cout << "********************" << endl;
cout << endl;
cout << "Type a guess between 1 and 20 then press ENTER" << endl;
cout << "Your guess: ";
cin >> g;
}
if (g = 1113) {
goto debugskip;
}
debugskip:
system("cls");
cout << "You have found the number!" << endl;
cout << "The number was " << n << endl;
cout << "Would you like to play again? 1 for yes, 2 for no.";
cin >> replay;
if (replay = 1) {
goto play;
}
else if (replay = 2) {
exit(1);
}
return 0;
}
You are using assignment operator instead of equals operator in your ifs.
Change
if (replay = 1) {
for
if (replay == 1) {
And do the same in the other places with the same problem.
Related
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;
}
}
Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}
Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.
I'm having a problem with the random generated number result not matching with the user input and it only outputs the first statements instead of falling to else if the user guessed wrong.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
int bank = 10;
int heads = 0;
int tails = 1;
char response;
string headsTails;
int coinToss = rand() % 2;
srand(static_cast<int>(time(0)));
cout << "Welcome to the coin flip game. It cost a dollar to play. " << endl;
cout << "If you guess correctly you will win $2.00 dollars " << endl;
cout << "Do you want to play? (Y/N) " << endl;
cin >> response;
while (toupper(response) == 'Y')
{
cout << "Your bank is $" << bank << " dollars." << endl;
cout << "Enter head or tails (H/T)" << endl;
cin >> response;
coinToss = rand() % 2;
headsTails = coinToss ? "Heads" : "Tails";
if (coinToss == heads || coinToss == tails)
{
cout << "Winner! The coin flip came up " << headsTails << endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank += 2;
}
else
{
cout << "Sorry, you lose. The coin flip came up " << headsTails <<
endl;
cout << "Would you like to play again? (Y/N) " << endl;
cin >> response;
bank -= 1;
}
}
cout << "Thanks for playing! Your bank is " << bank << endl;
cout << "Please come again! " << endl;
return 0;
}
if (coinToss == heads || coinToss == tails)
That condition is wrong, it will always evaluate to true since you set coinToss to 0 or 1 yourself.
You have to use the response variable you ask of the user, something like:
int guess = response == 'T' ? 1 : 0; // convert the user input to the same values used throughout the program.
if(guess == coinToss)
//won..
else
//lost..
I am having an issue learning C++ basics involving the while loop. When
I run my program it works well, until I get to the while loop involving an OR (||) statement. while (totalhumanHP > 0 || totalskeletonHP > 0) should continue until one hits zero then stop correct?
It is only keeping tabs on totalhumanHP and letting skeletonHP dip into the negatives without stopping. I am not sure how or why the OR statement isnt functioning in the while loop.
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int main()
{
cout << "-----SKELETMANS V HOOMINS-----\n";
int skeletonHP = 90;
int humanHP = 100;
int skeletonDMG = 1;
int humanDMG = 1;
int totalskeleton = 1; //Inputted Skele's
int totalhuman = 1; //Inputted hoomins
int totalskeletonHP; //Overall Skele HP
int totalhumanHP; //Overall Hoomin HP
string battlecry;
string battlecryenter;
default_random_engine generator(time(0));
uniform_int_distribution<int> skeletonrng(1, 22);
uniform_int_distribution<int> humanrng(1, 20);
cout << "How Many Skeletmans: ";
cin >> totalskeleton;
cout << "How Many Houmints: ";
cin >> totalhuman;
totalskeletonHP = totalskeleton * skeletonHP;
totalhumanHP = totalhuman * humanHP;
cout << "Overall Skeleton HP= " << totalskeletonHP << endl;
cout << "Overall Hoomint HP= " << totalhumanHP << endl;
cout << endl;
cout << "What is your battlecry?\n (You can use this to start the battle)";
cout << endl;
cin >> battlecry;
battlecry == battlecryenter;
cout << "Use Your Battlecry To Start The Fight!!!\n\n\n\n\n";
cout << "BattleCry: ";
cin >> battlecryenter;
if (battlecryenter == battlecry)
{
cout << "THE FIGHT HAS COMMENCED!!!\n\n\n\n";
}
else{
cout << "You 4got alreedy? UR DOMB MING\n\n";
cout << "ACTUAL BattleCry: ";
cin >> battlecryenter;
if (battlecryenter == battlecry)
{
cout << "THE FIGHT HAS COMMENCED!!!\n\n\n\n";
}
}
int endskeleton = 0;
int endhuman = 0;
while (totalhumanHP > 0 || totalskeleton > 0)
{
skeletonDMG = skeletonrng(generator);
humanDMG = humanrng(generator);
totalhumanHP = totalhumanHP - skeletonDMG;
totalskeletonHP = totalskeletonHP - humanDMG;
cout << "END SKELETON: " << totalskeletonHP << endl;
cout << "END HOOMING: " << totalhumanHP << endl;
}
cout << "Skeleton Ramaining Health: " << totalskeletonHP << endl;
cout << "Human Remaining Health: " << totalhumanHP << endl;
system("PAUSE");
return 0;
}
That's because you used OR, so even if skeletonHP is negative, that condition is still true since totalhumanHP is greater than 0.
Just change it with:
while (totalhumanHP > 0 && skeletonHP > 0)
When either one reaches 0, the loop will stop.