How to fix missing output in loops [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 3 years ago.
Improve this question
I'm new to C++ and I want to be able to run the program again as long as the user desires. But the problem is, whenever I loop the program, it doesn't show the outputs anymore. How do I fix this problem?
long numCoco = 0, numPeople = 0;
char again = 'Y';
do
{
cout << "enter the number of coconuts gathered: ";
cin >> numCoco;
//validate user input
while (numCoco < 1 || numCoco > 5000)
{
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "You have entered the wrong input\n";
cin >> numCoco;
}
if (!cin.fail())
break;
}
for (numPeople = numCoco - 1; numPeople > 1 && !found; numPeople--)
{
found = splitCoco(numCoco, numPeople);
if (found)
{
cout << numCoco << " Coconuts, " << numPeople << " Persons, " << " and 1 monkey\n\n";
}
}
if (!found)
{
cout << numCoco << " no solution\n\n";
}
cout << "Run again? (Y/N): ";
cin >> again;
} while (again == 'y' || again == 'Y');
Desired Output
Enter the number of coconuts gathered: 25
25 coconuts, 3 persons, and 1 monkey
Run again(Y/N): y
Enter the number of coconuts gathered: 30
30 coconuts, No solution
Run again(Y/N): N
Actual Output
Enter the number of coconuts gathered: 25
25 coconuts, 3 persons, and 1 monkey
Run again(Y/N): y
Enter the number of coconuts gathered: 30
Run again(Y/N): N

You must set "found" variable to 0 before the for loop.You expect "found" variable to be 0 when the input is 30 but actually the line:
found = splitCoco(numCoco, numPeople);
never executes in the second iteration.
The problem here is that after the first iteration(when input is 25), found is set to true and in the second iteration(when input is 30), found is still true so both the condition of "for loop" and the condition of the "if block" are false so none of them executes; so nothing is printed and the loop starts over.

Related

1.My problem in code is that when i input integers 75 and 100 it did not show my desired output [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 1 year ago.
Improve this question
/*when you will enter any number between 0-100 .
There are four ranges and the program will show in which range your number lies*/
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter your number between 0-100\n";
cin >> number;
if(number <= 25 || number == 0)
{
cout << "your number is between 0-25\n";
}
else if (number > 25 || number <= 50)
{
cout << "your number is between 25-50\n";
}
else if (number > 50 || number <= 75)
{
cout << "your number is between 50-75\n";
}
else if(number >75 || number <= 100)
{
cout << "your number is between 75-100\n";
}
else
{
cout<<"number is not between 0-100\n";
}
return 0;
}
The second if will always fire if the first if did not. Reason is it should not be OR, ||, but and AND, &&, same with the remaining tests.

Why is this code not working, How do i fix it? [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 4 years ago.
Improve this question
I am not sure if anyone can help me here but I am having a problem in my for loop and my loop continuation.
This is what the code is supposed to output.
Enter a starting integer value: 8
Enter an ending integer value: 121
Enter a positive increment: 17
Sum (using a while loop): 413
Sum (using a for loop): 413
This is what my code outputs.
Enter the starting integer value: 8
Enter the ending integer value: 121
Enter the positive increment: 17
Sum(using a while loop) = 413
Sum(using a for loop)= 110
Here is my code if someone can help me.
#include <iostream>
using namespace std;
int main()
{
//defining the integers
int startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting integer value: ";
cin >> startingNumber;
cout <<"Enter the ending integer value: ";
cin >> endingNumber;
cout <<"Enter the positive increment: ";
cin >> positiveIncrement;
//maiking sure the starting number is greater than 0
//also making sure the ending number is greater than
//the starting number.
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
int while_loop_Sum = 0;
//start of while loop
while_loop_Sum = startingNumber;
while ((startingNumber + positiveIncrement) <= endingNumber)
{
startingNumber += positiveIncrement;
while_loop_Sum += startingNumber;
}
cout << "Sum(using a while loop) = " << while_loop_Sum << endl;
//end of while loop
//start of for loop
int for_loop_Sum = 0;
{
for ((for_loop_Sum = startingNumber);((startingNumber +
positiveIncrement) <= endingNumber);(startingNumber +=
positiveIncrement))
{
for_loop_Sum += (startingNumber+positiveIncrement);
}
cout << "Sum(using a for loop)= " << for_loop_Sum;
//end of for loop
}
return 0;
}
Help would be greatly appreciated.
You never reset starting_number after the while loop! You cin >> startingNumber;, then in the while loop you startingNumber += positiveIncrement; and then you go on to use it in the for loop as if it's good, but it's not!
You need to store the actual starting number in a variable when you get it and then use some other temporary in the while and for to avoid this issue. Maybe something like:
cin >> startingNumber;
...
int tmpStarting = startingNumber;
while ((tmpStarting + positiveIncrement) <= endingNumber) {
...
}
...
tmpStarting = startingNumber; //Reset starting number for the for!
for(...

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.

Why does my "goto" loop? [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 8 years ago.
Improve this question
When I run this program, my output is just a loop of my cout. it as if the cin is now getting skipped? Does anybody have an idea as to why this is happening?
TryAgain:
cout<<"\nEnter a number greater than 1 and less than 100: "; // 21 - Request a Number
cin>>num; // 22 - Store the number
if (cin.fail()) {
cout << "Please enter a number!\n\n";
goto TryAgain;
}
if (num<=1){ // 24 - IF NUMBER IS BELOW 1
cout<<"Oh no, " << num << " is too small!\n\n"; // 25 - Print Error Message
return 0;
}
if (num>=100){ // 29 - IF NUMBER IS OVER 100
cout<<"Oh no, " << num << " is too large!\n\n"; // 30 - Print Error Message
return 0;
}
else if (isprime(num)){ //Call isprime // 34 - IF ISPRIME IS TRUE
cout << "True, " << num << " is a prime number!!\n\n"; // 35 - Print True Message
}
else{ // 38 - IF ISPRIME OS FALSE
cout << "False, " << num << " is not a prime number!!\n\n"; // 39 - rint False Message
}
When cin fails, it is put into an error state that will cause it to always fail. You need to clear that error state.
cin.clear();
If you're going to do the same input operation again, you also need to remove (at least some of) the previously entered data, or else cin will fail again.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You have to use two member functions of std::cin: ignore and clear. For example
#include <limits>
//...
if (cin.fail()) {
cout << "Please enter a number!\n\n";
cin.clear();
cin.ignore( numeric_limits<streamsize>::max() );
goto TryAgain;
}
Also it is a bad idea to use goto statement. You could write
do
{
if ( !cin )
{
cin.clear();
cin.ignore( numeric_limits<streamsize>::max() );
}
cout<<"\nEnter a number greater than 1 and less than 100: ";
cin>>num;
} while ( !cin );

What Is Causing Infinite While Loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am creating a game for two people to play to guess a number, I had it working with an if statement, but if player 2 gets it wrong I would like them to be able to guess again until they get it right. I decided to use a while loop, but I am getting an infinite loop of text, what can I do to stop it?
Here is my code: (I have commented out the if statement while working on the while loop)
#include <iostream>
using namespace std;
int main() {
int player1; //Number variable 1
int player2; //Number variable 2
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
system("pause");
system("pause"); //Keeps window on screen
return 0;
}
Also any feedback on how to make my code better would be highly appreciated.
You got two things wrong
The braces for the while loop.
You are not reading user input again in the loop.
Modify the loop as below..
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
The problem is that within the while loop you never change the value of player1 or player2. Hence if they are unequal the first time they will be forever unequal and the code will loop infinitely. To fix this you need to move the code which changes the values into the body of the loop. Hence the user has a chance to change the values.
do {
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
if (player2 == player1)
cout << "Correct!" << endl;
else
cout << "Wrong, try again" << endl;
} while(player2 != player1)
If you don't use an open brace after the while statement it only refers to the following expression.
Additionally, after the while you are not reading data from the user again, so how do you expect player2 to ever change?
In terms of code organisation it would be better to set player2 to something obviously invalid, like -1, and have the while at the beginning, without the previous read and if statement so it doesn't have to be special cased.
Try this...
do
{
cout << "Player 2 guess the number between 1 and 100: "; //Asks guess a number
cin >> player2;
} while (player2 != player1)
Your curly brackets are in the wrong position and you never read input from the player after the first time.
if you change it like this, the second player will be asked again.
....
while(player1 != player2){
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}
In addition, you should add some basic error handling, for example checking if the cin.error() flag is set.
Your while has no brackets, which makes the line right after it repeat forever!
Put the cout and cin for player 2 guess inside a do-while loop and then verify the condition.
cout << "Player 1 type in a number between 1 and 100: "; //Asks player to enter a number
cin >> player1;
system("CLS");
do {
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
} while(player2 != player1);
In
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
Nothing in the loop ever changes player2 nor player1, so if the condition player2 != player1 was true, it will remain true.
The loop
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
}
is an endless loop, because the variables player2 and player1 are not changed inside of the loop. If the while condition is true when entering the loop, it will stay true forever.
UPDATE:
To allow player2 to guess repeatedly, and hence change the number that he guessed and get out of the while loop, add cin >> player2; after the cout statement:
while(player2 != player1)
{
cout << "Player 2 guess the number between 1 and 100: ";
cin >> player2;
}