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.
Related
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;
}
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.
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 4 years ago.
Improve this question
I seem to be looping through my array wrong, I've got it set up to prompt the user for a list of numbers and I am supposed to be comparing it to another number that the user sets.
#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: \n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "\n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}
I assume the following code is where the problem lies. The idea is i set s = 2 enter in a list of numbers and then compare to s and print s if there is a match if not I print No match found. When I enter in a number that i know matches s it seems to print the first number in the array, but i thought since I loop through the numbers one by one in the for loop that it should display when it reaches the right number not when it stops. Thanks in advance
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
You are using a single equals sign. This is setting s to userArray[i] so it always evaluates to true. For comparisons, use double equal signs, like this:
if (s == userArray[i]) {...}
Also, your return statement is inside your loop (credit to #UnholySheep).
you are comparing with a single assignment operator = you should be using the equal operator instead ==
if (s = userArray[i]) with in the for loop is one example.
you also doing the same mistake in
if (chk = true)
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 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.