how do I use else and if statements [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
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.

Related

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)

Issue with a for loop (C++, Visual Studio [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have only really been coding for a few days, though I've reading the textbook for my Intro to C++ class for two weeks. I'm having an issue with an assignment, and I feel like I'm missing something super simple, but I can't understand what I've done wrong.
The exercise calls for you to 'write a program that reads numbers from cin, and then sums them, stopping when 0 has been entered.'
The professor told us we could write it with a for loop, a while loop, or a do-while loop. I am trying to write it with a for loop.
The program compiles successfully, it allows me to enter multiple values, and it sums it correctly. It also stops on no successfully. The only thing that's wrong with it is when I enter 0, it does not stop the program. I have tried using different commands inside the for loop, such as goto, and trying to direct it to go to break; when the value entered is zero, but my knowledge is shoddy, to say the least. I've read the textbook but I don't have enough experience yet, and I don't remember everything, and I can't figure out what I'm doing wrong.
This is what the program looks like:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
char indicator{ 'n' };
double value{};
double sum{};
for (;;)
{
cout << endl
<< "Enter a value here: ";
cin >> value;
sum += value;
cout << endl
<< "Do you want to enter another value (enter y or n)? ";
cin >> indicator;
if (('n' == indicator) || ('N' == indicator))
break;
}
cout << endl
<< "The sum of the values you entered is " << sum << "."
<< endl;
return 0;
}
Please point out my stupid mistake, I'd be grateful to learn. Thank you!
There is no sense to ask the user each time whether he wants to continue.
So I would write the loop the following way
cout << "Enter a sequence of real numbers (0 - exit): ";
for (;;)
{
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
Also as the variable value is used only in the body of the loop it should be declared there. So the loop can look like
cout << "Enter a sequence of real numbers (0 - exit): ";
for (;;)
{
double value;
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
An alternative for this for loop is while loop of the following form
cout << "Enter a sequence of real numbers (0 - exit): ";
while ( true )
{
double value;
if ( !( cin >> value ) || ( value == 0.0 ) ) break;
sum += value;
}
Just compare value to zero after it is inputted:
for (;;)
{
cout << endl
<< "Enter a value here; enter 0 to stop: ";
cin >> value;
if(value==0.0) break;
sum += value;
}
I would like to make a few suggestions to you which you may find helpful.
To begin, any of the loops you mentioned (for, while, do while) may be used in solving this problem. But I believe that the do while lends itself best to this particular problem.
The use of a for is especially bad for this exercise as for loops are typically employed while performing iterations over a set of values or some sort of finite counting. Being asked to perform an action an indefinite number of times is better suited for a while or do while.
Just look at your for declaration:
for(;;)
{
// ...
}
What benefit does using for have in this situation if you make use of none of it's functionality.
Second, the use of double is for your value and sum is not recommended either. This is because of something called floating-point precision. You can not reliably compare a double value using ==. See: What is the most effective way for float and double comparison?
Instead, unless specified by the problem statement, I would opt to use an integer value type. Either int or unsigned int.
Third, you are not correctly initializing your variables. Instead, it should be done as:
int value = 0;
int sum = 0;
Improper variable initialization can lead to countless bugs and is a very common source of problems.
Finally, I would recommend against the use of using namespace. This is used commonly by beginner developers who then are taught better practices and then have to unlearn the behavior. See: Why is "using namespace std" considered bad practice?
Taking this advice into consideration would lead to a solution such as:
#include <iostream>
int main(int argc, char** argv)
{
int sum = 0;
int value = 0;
do
{
sum += value;
std::cout << "Please enter a value: ";
std::cin >> value;
} while(value != 0);
std::cout << "The sum of all values entered is: " << sum;
return 0;
}
ITNOA
You can just change
cout << endl
<< "Do you want to enter another value (enter y or n)? ";
cin >> indicator;
if (('n' == indicator) || ('N' == indicator))
break;
with
cout << endl
<< "Do you want to enter another value (enter 0 for exit or not zero to continue)? ";
int indicator = -1;
cin >> indicator;
if (indicator == 0)
break;
If you do not want to ask user to continue enter new value in every time #Govind Parmar and #Vlad from Moscow write cleaner code than you write.

C++ While Loop Break [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
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).

while statement is unable to read the correct char input

hi i am new to c++ and i dont understand why my while statement doesnt work now. it was working when i tried to do it earlier.
Full code is available at: http://pastebin.com/aeH5fKwh
basically here is the while loop (i excluded all the unnecessary parts, i left the inside of the while loop intact for viewing purpose)
int main()
{
unsigned int seed;
char input;
bool done;
for (int round = 0; round < 5; round++)
{
done = false;
cout << "\nEnter seed: ";
cin >> seed;
cout << "\nRound 1" << endl;
while(!done)
{
cout << "\nDo you wish to draw another card [y][n]: ";
cin >> input;
while (input != 'y' && input != 'n')
{
cout << "Invalid input! Please enter [y][n]!" << endl;
cin >> input;
}
if (input == 'y')
{
dealExtra(playerHand, deck, gameInfo);
cout << "Your cards are ";
printHand(playerHand, gameInfo.playerCardCount);
}
else
done = true;
}
}
cout << endl;
return 0;
}
when i try entering anything that is not 'y', 'n', it will tell me that my input is invalid. But when i try to enter 'y' or 'n', it kinda just ignored it and nothing else happened.. i checked with cout statement and found that it manage to get into the if (input == 'y') statement, but it doesnt seem like it is doing anything else. Everything was fine till 20 minutes ago and i really couldnt figure out whats wrong.
Edit: i ran another test using "cout << '[' << input << ']' << endl;".. it seems like the program is able to get my first input, but then it just hangs there afterwards.. what i get is something like:
Do you wish to draw another card [y][n]: y
[y]
y
y
y
y
I compiled this on linux terminal using g++
if extra codes is needed, i'll edit and add them.. thanks!
When you ask for input from the console, most implementations buffer characters until a newline key is pressed.
After the newline is received, the first character of the buffer is returned. The newline still remains in the buffer as well as any extra characters.
In your case, the second cin >> input statement will read the newline from the buffer.
As an experiment, try entering "frog" and single step through your program. This should illustrate the case of residual characters in the buffer.
Try cin.ignore(1000, '\n') after the first cin >> input. The ignore method will eat up any remaining characters in the buffer until the newline is found.
Make below statements inactive
dealExtra(playerHand, deck, gameInfo);
printHand(playerHand, gameInfo.playerCardCount);
and check if it works, then try making one of the above statements active alternately to find out in which function the flow is getting lost. And so on.
If you feel lazy to run a debugger, and plan to use cout<< statements to find a hanging call, you should flush you cout:
( cout << "I am here and going to hang" ).flush() ;
Otherwise you can't see recent output just because it's still in the output buffer. Try this and you well might see what call hangs your program.
You have an infinite loop inside checkComputerHand:
bool done = false;
while(!done)
{
if(sum == 11 && checkAce == true)
{
computerHand[aceLocation].value = 11;
done = true;
}
if(sum > 11 && checkAce == true)
{
computerHand[aceLocation].value = 1;
done = true;
}
// What if checkAce wasn't true? Infinite loop!
}
Also, the first two lines of newGame do not make any sense:
void newGame(Card playerHand[], Card computerHand[], Statistics &gameInfo)
{
playerHand = '\0';
computerHand = '\0';
// ...
}
Array parameters are silently rewritten by the compiler as pointer parameters. So all you're doing is assigning the null pointer to those local pointers. Probably not what you intended...

C++: function wont stop looping [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
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) {