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.
Related
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 would like to improve the code below. I would like to use try-catch statement to validate the input letters. An error message should be printed in case the user inputs an invalid letter.
I have two methods: showMenu and selectOperation.
The methods:
//Show Operations in menu
void showMenu()
{
cout << " Select an option: \n\n"
<< "1 = Register new customers \n"
<< "2 = Register new products \n"
<< "3 = Add Product Existence \n"
<< "4 = Register a new purchase \n"
<< "0 = Exit \n\n";
}
//Select an Operation from menu
int selectOperation()
{
int selectedOperation = 0;
do
{
showMenu();
cin >> selectedOperation;
if ((selectedOperation < 0) || (selectedOperation > 4))
{
cout << "\n You have selected an invalid option"
<< "...Try again \n";
system("pause");
system("cls");
}
} while ((selectedOperation < 0) || (selectedOperation > 4));
return selectedOperation;
}
How should I do this?
You usually don't want to get and handle exceptions for invalid input.
Using exceptions to control regular flow of a program is a well known design flaw/anti pattern.
The idiomatic way is to check the input streams state:
// is true for non integer input and numbers outside the valid range
while(!(cin>>selectedOperation)) {
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
The exception variant looks like this (way more complicated and less concise IMO):
cin.exceptions(std::ifstream::failbit);
bool validInput;
do {
try {
validInput = true;
cin>>selectedOperation)
}
catch (std::ios_base::failure &fail) {
validInput = false;
// Cleanup the stream state
cin.clear();
std::string dummy;
cin >> dummy; // Consume the invalid input
cout << "Please input a number." << std::endl;
}
} while (!validInput);
You have to clear the input stream in any way from fail() state.
You could also do this with a if else if statement...
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
#include <iostream>
#include <string>
using namespace std;
int main ()
{
do
{
string name, answer;
cout << "Welcome to the prime number checker! Please enter your name: ";
getline (cin, name);
int a;
cout << "\nHello " << name;
cout << "\nPlease enter an integer: ";
cin >> a;
cin.sync();
if (a == 2)
{
cout << "\nThis is a prime number" << endl;
}
else
{
for (int b = 2; b < a; b++)
{
if (a % b == 0)
{
cout << "This number is not prime number" << endl;
break;
}
else
{
cout << "This number is a prime number." << endl;
break;
}
}
}
cout << "Do you want to do this again (Yes or No)?";
getline (cin, answer);
}
while (answer == "yes" || answer == "YES" || answer == "Yes"); //Not declared in this scope
return 0;
}
You declared answer within the do block. But then try to reference answer outside of that scope block.
Declare answer at the top of main instead of in the do block.
You need to move the declaration of answer outside the loop:
string answer;
do {
string name;
...
} while (answer == "yes" || answer == "YES" || answer == "Yes");
If you declare it inside the loop, it no longer exists by the time the while clause is evaluated.
As other people said, the "answer" variable only exists inside the loop - it isn't accessible from outside it.
One other recommendation: rather than checking every possible permutation of capitalization just cast the whole string to lowercase. (You actually missed several - there are 6 total because each position could have one of 2 possible values. Presumably something like "YeS", for example, should still be accepted as "yes").
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> ¤tGuessPegs, 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.
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 8 years ago.
Improve this question
My goal is to create a C++ program that executes a chunk of code repeatedly until the user enters in an appropriate value and does so with the use of a while loop. My code is just repeating over and over and even if I input a "0" it still repeats the chunk of code in the loop.
Here is my source code:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
bool repeat = true;
while (repeat = true)
{
cout << "Please select an option." << endl;
cout << "[1] Continue Program" << endl;
cout << "[0] Terminate Program" << endl;
cout << "---------------------" << endl;
repeat = false;
cin >> num;
cout << endl;
if (num = 1)
{
repeat = true;
//execute program
}
else if (num = 0)
repeat = false;
else
cout << "Please enter an appropriate value.";
}
return 0;
}
while (repeat = true)
^^
is one of your problems:
while (repeat == true)
^^
With an assignment, the condition always evaluates to a true.
Some people advocate using Yoda condition to avoid these typos. Another way is to simply compile your program with the highest warning levels:
-Wall
Check your operators. You're using the assignment operator = instead of the comparison operator == in your while and if arguments.
while (repeat = true)
In the while condition, you are using the assignment operator =, not equality ==.
It's valid C++ syntax, but not what you expected. repeat is assigned to true, so the condition is always true.
The same error exists in if (num = 1) and else if (num = 0).
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.