C++ While Loop Break [closed] - c++

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).

Related

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.

cout won't print in function [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 5 years ago.
Improve this question
I'm pretty new to programming so this might be a question with an obvious answer for you guys and I'm really stumped, why doesn't cout work in the following function? I've included the iostream header so I'm assuming it has something to do with it being in the function?
int inputFileData(song musicLibrary[])
{
char discard = ' ';
int counter = 0, length = 0;
ifstream inData;
inData.open("songs.txt");
if (!inData)
{
cout << "Error: No input file found " << endl;
cout << "Program terminating..." << endl;
return 1;
}
while (!inData.eof())
{
inData.getline(musicLibrary[counter].title, ARRAY_CONST, ';');
inData.getline(musicLibrary[counter].artist, ARRAY_CONST, ';');
inData >> musicLibrary[counter].durationMinutes;
inData.get(discard);
inData >> musicLibrary[counter].durationSeconds;
inData.get(discard);
inData.getline(musicLibrary[counter].album, ARRAY_CONST, '\n');
length = strlen(musicLibrary[counter].album);
if (length = 0)
{
cout << length << endl; //This cout object doesn't work in this function
break;
}
else
counter++;
}
return counter;
}
The line if (length = 0) should be if (length == 0).
Elaborating Eli's answer:
if (length = 0)
Assigns the value 0 to length and then evaluates the expression. Since the expression returns 0 the condition evaluates to false and you don't enter the if clause.
Instead, use if (length == 0)

What does it mean by "error: not declared in this scope?" [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 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").

important solution for a while loop [duplicate]

This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 7 years ago.
Guys why this code become an infinite loop? I'm learning C++ so if you can explain the solution, for me would be very important!
// Odd_or_Even.cpp : This program determinate if a number is Odd or Even
//
#include "stdafx.h"
#include "std_lib_facilities.h";
int main()
{
int num = 0;
bool repeat = true;
while (repeat == true)
{
cout << "Please enter an integer to determinate if it's odd or even: ";
cin >> num;
cout << "\nReading data...";
if (!cin) {
cout << "Failed\n";
cout << "There is some problem with the number, sorry!\n";
cout << "\n";
cin.clear();
}
else
{
cout << "God job, now stop lose time.";
repeat = false;
}
}
keep_window_open();
return 0;
}
Thanks!
EDIT: ok i writed the if for block the loop, but if you try to write a letter, instead of a number, it still go in a loop!!
It's an infinite loop because you never update repeat. Your while loop will continue to run until repeat is set to equal 0 or false.
P.S. since repeat is a Boolean value, while(repeat) is the same as while(repeat==true)
Your code sets repeat to true and then your while loop runs while
while(repeat == true)
To get it out of an infinite loop you need to do this somewhere inside the while loop:
repeat = false;
On what condition would you like to break out of the loop?