C++: function wont stop looping [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
The purpose of this function is to ask the user to input a quantity to add to an order. The function will ask them to reenter info if they input a value less than 0 and exit the function if they input 0. It accepts user input if the value is a positive integer, modifies the data member, and returns true. If the user inputs 0, the function returns false. Problem is, the program never exits no matter what the user inputs. 0, a value less than 0, and a valid positive integer all cause the function to loop and ask the user to input information again. Can someone point out what is wrong with the logic within this function to explain why this would be happening?
bool Order::add(std::istream& is) {
int quantity;
bool start = true;
bool val = false;
while (start = true) {
std::cout << "Enter quantity (0 to quit): ";
is >> quantity;
if (quantity == 0) {
std::cout << "**No delivery recorded!" << std::endl;
start = false;
}
else if (quantity < 0) {
std::cout << "quantity must be a positive integer" << std::endl;
}
else {
copies += quantity;
start = false;
val = true;
}
}
return val;
}

You are always assigning true to the "start" variable:
Change the while loop (==):
while (start == true) {

Related

how do I use else and if statements [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
both of my options are coming up when I run the code
I have tried two if statements else if and else
cout << "would you like to hit or stand?" << endl; //asking if you would ike to hit or stand
bool hit; //the hjitting opption
bool stand; // the stand / hit option
cin >> hit, stand; // the avaiabillity for hitting or standing (player input)
if ( hit = true) // if you hit
{
for (n = 1; n <= 1; n++) //loop for how many cards are you have
{
num = rand() % 13; //get random number
cout << num << "\t"; //outputting the number
}
}
{
cout << "you stand \n"; // saying you stand
I expect the code to output the number when u say hit and say you stand when you say stand but it is out putting either just the hit just the stand or bothenter code here
The snippet:
bool hit;
bool stand;
cin >> hit, stand;
does not magically set one of the booleans based on what you enter. Your cin statement will attempt to get two separate booleans from the user.
What you probably want to do is get a string on then act on that, something like:
std::string response;
std::cin >> response;
if (response == "hit") {
do_hitty_things();
} else if (response == "stand") {
do_standy_things();
} else {
get_quizzical_look_from_dealer();
}
In addition (though irrelevant if you take my advice), the expression hit = true is an assignment rather than a comparison. A comparison would use ==. The result of if (hit = true) is to first set hit to true and then use that as the condition. Hence it will always be true.
Also see here for the absurdity of explicitly checking booleans against true and/or false.
Hit or stand is one choice so you need one boolean variable.
bool hit;
cin >> hit;
hit is a boolean variable so it's already true of false, you don't need to compare it with true (or false). So just if (hit) is OK. If you were to compare it with true then it's == not =, so if (hit == true) would be OK as well.
Finally since your choice results in two alternatives you need an if ... else ... statement.
if (hit)
{
for (n = 1; n <= 1; n++) //loop for how many cards are you have
{
num = rand() % 13; //get random number
cout << num << "\t"; //outputting the number
}
}
else
{
cout << "you stand \n"; // saying you stand
}
When you are still learning the basics of C++ syntax and rules you need to write smaller amounts of code. Even in this short program you had multiple errors and it's hard to figure out what's wrong when that happens. At this stage you should literally be writing one line of code at a time. Test that to make sure it's works before you write the next line.

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
string word;
int l,eFound,xFound;
l = word.size();
cout <<"Enter a word: ";
cin >> word;
for (l>0 ; word.at(l)!='x' || word.at(l)!='e'; l--)
if (word.at(l) == 'e'){
eFound = true;
}
else if (word.at(l) == 'x'){
xFound = true;
}
if (eFound == true && xFound == true){
cout << "Your word, "<<word<<", contains the character 'e'"<<"\n";
cout << "Your word, "<<word<<", contains the character 'x'";
}
if (eFound == true && xFound != true){
cout << "Your word, "<<word<<", contains the character 'e'";
}
if (xFound == true && eFound != true){
cout << "Your word, "<<word<<", contains the character 'x'";
}
I'm not sure what is going on I'm trying to use a for loop to detect either e or x in a input of some word. I've clicked on other pages with the same error but they have different codes and I don't really understand what is explained. So what is causing this error? I'm 2 weeks into my first programming class, sorry if I'm asking a dumb question.
The issue is that indexing of std::string starts from zero. Not from 1. So, word.at(l) will crash if l = word.size();.
You should change the statement to: l = word.size() - 1;.
Also, Change your loop condition to for (; l >= 0 ; l--)
Suggestion:
Please go for library functions:
Like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cout <<"Enter a word: ";
cin >> word;
bool eFound = word.find('e') != string::npos;
bool xFound = word.find('x') != string::npos;
if (eFound) {
cout << "Your word, "<<word<<", contains the character 'e'" << "\n";
}
if (xFound) {
cout << "Your word, "<<word<<", contains the character 'x'" << "\n";
}
return 0;
}

Having trouble looping through an array in c++ [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 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)

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.

While loop not working in program with boolean (C++) [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 8 years ago.
Improve this question
Hi I was writing a simple program that asks for user input within a certain range. I used a boolean to start the while loop, but when I try declaring the boolean false in the first if statement, it doesn't end the loop and the program keeps asking for a user input. I've thought about using a break but shouldn't negating the condition stop the loop?
int num;
cout << "Enter a number";
bool invNum= true;
while (invNum = true)
{
cin >> num;
if (num >= 0 && num <= 20)
{
cout << "You typed: " << num << endl;
invNum = false;
//break;
}
if (num <= 0 || num >= 20)
{
cout << "Type another number: ";
}
}
return EXIT_SUCCESS;
}
= is not used for comparison. You should use ==. Change while (invNum = true) to while (invNum == true) or better to write while (true == invNum)
while (invNum = true)
Here is the problem.
It should read:
while (invNum == true)
What you're currently doing is assigning true to invNum. The assignment statement invNum = true returns the value of invNum after it has been set to true, in effect resulting in a while(true) loop.