Cannot exit while loop with boolean condition c++ [closed] - c++

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 8 years ago.
Improve this question
Hi this is my first post. I apologize if I'm not following certain rules or conventions. If that is the case please let me know.
I have a game which runs in a while loop until the score limit is reached by either player, at which point the other player has one last (iteration) chance to beat the first players score. However after the score limit is reached, the loop continues to run and the winner is never checked.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
int roll();
int playTurn(int);
int main(){
const int LIMIT = 5;
int whoseTurn = 1;
int pnts1 = 0;
int pnts2 = 0;
bool suddenDeath = false; //True when score limit is reached
while(!suddenDeath){
if(pnts1 >= LIMIT || pnts2 >= LIMIT){ //Limit was reached by previous player.
suddenDeath == true; //Next player has 1 turn to win
}
if(whoseTurn == 1){
pnts1 += playTurn(whoseTurn); //Play turn and tally points
whoseTurn = 2; //Swith player for next iteration
}
else if(whoseTurn == 2){
pnts2 += playTurn(whoseTurn);
whoseTurn = 1;
}
cout << "-------------------------------------" << endl //Display score
<< "Player 1 has " << pnts1 << " points" << endl
<< "Player 2 has " << pnts2 << " points" << endl
<< "-------------------------------------" << endl << endl;
};
if(pnts1 > pnts2)
cout << "Congratulations Player 1! You won with a score of: " << pnts1 << " - " << pnts2;
else if(pnts2 > pnts1)
cout << "Congratulations Player 2! You won with a score of: " << pnts2 << " - " << pnts1;
else if(pnts1 == pnts2)
cout << "A tie! What are the chances?";
return 0;
}

suddenDeath == true;
// ^^
is an expression meaning "compare those two values", which is then thrown away. The C statement 42; is equally valid, and equally useless (a).
You want to assign the value, so you'd use:
suddenDeath = true;
// ^
It's actually the other end of the much more common if (a = 0) problem where people assign rather than compare.
(a) If you're wondering why anyone in their right mind would allow this into a language, it actually allows for some powerful constructs with minimal code.
And, you've seen it before most likely. The statement i++; is such a beast. It's an expression giving i (which you throw away here) with the side effect that i is incremented afterwards.

suddenDeath = true;
Use a single = for assignment. == is used for condition check.

Related

Why the output of my code has 4745728 as the output? [closed]

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 1 year ago.
Improve this question
I'm making a simple program to count user balance whenever there's a positive integer input between 1-5 from user. I only make the code for the first option, but something weird is happening from the output, here's my code :
#include <iostream>
using namespace std;
int balance = 100000;
int iNet = 59900;
int internet(int iNet, int code, int remain){
if(code == 1){
remain = balance - iNet;
cout << "Price = " << iNet << endl;
cout << "Remaining credit = " << remain <<endl;
}
}
int main(){
int code, remain;
cin >> code;
cout << internet(iNet, code, remain);
return 0;
}
But when i run the program, it shows like this :
user input
1
program output
Price = 59900
Remaining credit = 40100
4745728
I have no idea where's the 4745728 coming from.
If you don't want to return anything from a function, make the return type void:
void internet(int iNet, int code, int remain){
// ^
if(code == 1){
remain = balance - iNet;
cout << "Price = " << iNet << endl;
cout << "Remaining credit = " << remain <<endl;
}
}
Then compiler will not allow you to print a rubbish value anymore and you will have to fix your main:
int main(){
int code, remain;
cin >> code;
internet(iNet, code, remain);
//^ don't print anything, just call the function
return 0;
}

Why won't my "main()" function call a void function? [closed]

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 3 years ago.
Improve this question
I'm working on a program to aid me in world-building that randomly generates a settlement (hamlet, village, town, city) based on a nation (German, Latin, Eastern) that the user chooses. Unfortunately, my code halts right at the "main()" function as it won't call the "settlementCreation()" void function I created.
I've tried moving the function I want to call above the "main()" function, or my usual method of creating the function above, defining it's contents below, but neither of these are working. I can't figure out any other solutions with my limited experience coding C++.
Main() Function:
int main() {
char tempChoice{};
bool isMakingSettlement = true;
while (isMakingSettlement = true) {
cout << "Create a settlement? (y/n): ";
cin >> tempChoice;
cout << "\n\n";
if (tempChoice == 'y') {
settlementCreation();
} else {
isMakingSettlement = false;
}
}
return 0;
}
settlementCreation() Function:
void settlementCreation() {
int tempType{};
int tempNation{};
bool isTypeValid = false;
bool isNationValid = false;
while (isTypeValid = false) {
cout << "What type of settlement would you like to create?:";
cout << "\n 1. Hamlet";
cout << "\n 2. Village";
cout << "\n 3. Town";
cout << "\n 4. City\n";
cin >> tempType;
if (tempType >= 1 && tempType <= 4) {
isTypeValid = true;
} else {
cout << " is an invalid choice, please select a valid choice.";
}
cout << "\n\n";
}
while (isNationValid = false) {
cout << "What nation would you like your settlement to be in?: ";
cout << "\n 1. Latin";
cout << "\n 2. German";
cout << "\n 3. Eastern\n";
cin >> tempNation;
if (tempNation >= 1 && tempNation <= 3) {
isNationValid = true;
} else {
cout << " is an invalid choice, please select a valid choice.";
}
cout << "\n\n";
}
Settlement objSettlement(tempType,tempNation);
}
So the program is supposed to allow the user to choose a nation and a settlement type before redirecting to the Settlement object constructor to create the objSettlement instance of the object.
The usual outcome however, is just an infinite loop of:
"Create a settlement? (y/n): "
With no responses I've tried closing the program or going to the "settlementCreation()" function.
while (isMakingSettlement = true) {
This does not check if isMakingSettlement is true. It sets isMakingSettlement to true! This means the check in the while loop always sees true, so never stops going round.
Use while (isMakingSettlement == true).
(Or while (isMakingSettlement), or while (true == isMakingSettlement); all are fine, it's a stylistic choice, though the last would have helped you catch this bug!).
Similarly for all your other while loops.
Assuming you fix the above, your next problem will be here:
bool isTypeValid = false;
bool isNationValid = false;
while (isTypeValid == false) { // once corrected
// ... never get here!
while (isNationValid == false) { // once corrected
// ... never get here!
You always set those bools to false, so these loops are never executed.

Conditional statement outputting the wrong command [closed]

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 3 years ago.
Improve this question
Beginner here so I'm sorry if I made nooby mistakes
I assign di to be the array myworld[] depending the the user input it'll assign the di into the appropriate array position, but for some reason the if statement keep outputting "make" instead of "change" when my input is 'c'
I tried to remove else if and put if for all of them, or got rid of else if and just use else.
#include <iostream>
using namespace std;
int main() {
char di;
char myword[] = {'d','m','s' ,'c'};
do {
cout << "Make a selection:" << endl;
cout << "d - insert 1$ bill" << endl;
cout << "m - view menu" << endl;
cout << "s - select an item" << endl;
cout << "c - get change" << endl;
cin >> di;
if (di == 'd')
di = myword[0];
else if (di == 'c')
di = myword[3];
}while (!myword);
if (myword[0])
cout << "make";
else if (myword[3])
cout << "change";
return 0;
}
Probably you forgot to make a comparison inside if statement. For now you are just saying if('d'!= 0) which is always true. Perhaps you tried to make if(di == myword[0]). The same applies for the else if statement.

C++ maze count passing time [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've created functioning maze game in c++ in console.
I would like to add function to count time needed to pass the maze by player.
Total time could be displayed after pass the maze.
I would really appreciate any help or ideas.
main game-loop looks something like that:
do {
show(); // function do display maze , 2d array
cout << "Your position: " << x << " " << y << endl;
cout << "Coins gained: " << coins << endl;
cout << "blahblahblah" : "<<endl;
m = getche();
cout << endl;
move(m); // function to recognize which way player want to go, including checking for not going through the wall
cout << endl;
system("CLS");
} while (x != 12 || y != 18 || coins < 10); //for pass the maze player have to move on these position and gain x coins
system("CLS");
cout << "You Won!" << endl;
cout << "Click enter to move on. \n";
#include <time.h>
#include <iostream>
int main () {
int start, end, total;
start = time(NULL);
//place loop here
//game ends, calc time
end = time(NULL);
total = end - start;
std::cout << "You completed the maze in " << total << " seconds.";
return 0;
}
Essentially, what this does is start counting time at a certain point, then stop counting at a later point (in seconds), though cin and getch(), or anything else that pauses the program in order to get an input may cause the timer to stop. In certain libraries, it will use system time. In other libraries, it will use running time. Be careful of this, and if it does use running time, be sure to use an input method such as
int main(){
time_t myTime,myTimeEnd;
time(&myTimeEnd);
myTime = myTimeEnd;
//code
time(&myTime);
int total = myTimeEnd - myTime;
std::cout<< "Time taken is " << total << " seconds.";
return 0;
}
The second method gets and holds the time for you, which is saved by passing your time variable by reference to the time function, which 'gets' time.

Vector is not clearing [closed]

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 7 years ago.
Improve this question
I have created a function that gets a series of guesses (a sequence of colors) from a user and puts them in a vector, and this function is called within a while loop in main().
Each time it is called by the while loop, the guess should be cleared before being refilled with inputs. However, within the second loop, entering a color I entered during the first loop activates my error message ("Invalid or repeated color entry..."), suggesting that the vector was not successfully cleared.
I've tried to clear it with a space, various strings, etc., but nothing seems to clear it. What am I missing?
Function:
void getGuess(vector<string> &currentGuessPegs, vector<string> &colorChoices, int maxPegSlots) {
string input; // stores input temporarily
// ---clear previous guess---
for (int i = 0; i < maxPegSlots; i++) {
currentGuessPegs[i] == "";
}
// ---prompt player for each peg guess and store in currentGuessPegs---
for (int i = 0; i < maxPegSlots; i++) {
cout << "Peg " << i+1 << ": ";
cin >> input;
while (find(currentGuessPegs.begin(), currentGuessPegs.end(), input) != currentGuessPegs.end() // Loops if color entry has already been used
|| find(colorChoices.begin(), colorChoices.end(), input) == colorChoices.end()) { // or is an invalid choice
cout << "Invalid or repeated color entry. See color choices and re-enter a color you have not used.\n";
cout << "Peg " << i + 1 << ": ";
cin >> input;
}
currentGuessPegs[i] = input;
}
}
And here is my call to the function from main():
// ---get and check guesses until maximum # of guesses is exceeded or solution is guessed---
while (guessCount < maximumGuesses && solutionGuessed == false) {
getGuess(currentGuess, colorOptions, numberOfPegs); // get the guess
solutionGuessed = checkGuess(currentGuess, solution, numberOfPegs, red, white); // check the guess; returns true if solution was guessed
cout << "r: " << red << " w: " << white << endl << endl;
guessCount++;
}
currentGuessPegs[i] == "";
// ^^
Whoops.