why wont this do while loop exit after accepting input - c++

Pretty straight forward. i dont understand why it wont quit the loop after not accepting a y char.
ive tried different variations of == and != with regards to y char and n char
vector<int> v;
char ans;
do
{
cout << "Enter scores, enter number outside of 0-100 to stop:\n";
get_scores(v);
print_stats(v);
cout << "Do you want to try another set of scores? Y/N: \n";
cin >> ans;
} while (ans != ('n' || 'N'));
after typing any char, the loop keeps asking for more input.
NOTE: the get scores and print stats functions work as their supposed to.

Your comparison in the while condition is not correct, you probably meant to do
while (ans != 'n' && ans != 'N');
('n' || 'N') will be coerced to true (1), so you would check for a char of value 1 instead of 'n' / 'N'

} while (ans != ('n' || 'N'));
Here you are comparing char with boolean result of || operation for the 2 other chars.
Which alway evaluates as true.
So your while statement is effecitvely
} while (ans != true);
to fix this you need to compare ans to both of the n and N and exit if one of them becomes true, for example:
} while ((ans != 'n') && (ans != 'N'));

while (ans != ('n' || 'N')) is the same as writing while (ans != (true)). You probably wanted while ((ans != 'n') && (ans != 'N')).

Related

C++: Having troubles with do while loop

do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' || 'C');
I have account_type set as char,the problem is that everytime i run the program and i input S or C the loop keeps repeating.Can anyone help me know why its happening?
All non-zero values in c++ evaluate to true when used in a boolean operation. So account_type != 'S' || 'C' is the same as account_type != 'S' || true. Which means your loop never exits.
What you need to do is to preform both checks
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
Its because you cant say 'S' || 'C', you would think c++ would think that you mean if account_type is S or C however c++ looks at this in 2 separate sections: (account_type == 'S') || ('C'). ('C') will default to true therefore the loop loops forever.
What you need to write is:
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
You need to change the || to && because if account_type is S then it cant be C and the same vice versa therefore the loop never finishes.
Your while check is wrong. You have to write it like this:
while (account_type != 'S' || account_type != 'C')
You can't perform || checks, or any for that matter like that, you must always re-state the variable.

How to (not) rerun c++ code?

I am doing the basic console c++ "do u want to rerun program?" dance,
and failing. This is what I'm using
int main()
{
char repeat = 'y';
while (rep == 'y' || 'Y')
{
{
//primary code is here
}
cout << "\n\tRerun program? y/n";
cin >> repeat;
if (rep == 'n' || 'N')
{cout << "\n\tExiting program\n";}
}
return 0;
}
When my program finishes, it restarts and outputs "Exiting program"
no matter what I input at "Rerun program?"I understand this has
something to do with flushing or resetting the char "repeat"?
No idea how to do that and google isn't helping.
I can submit the primary program code on request, but I doubt it has
anything to do with this error.
if (rep == 'n' || 'N') will be always true,
because it actually doing if( (rep =='n') or 'N') ('N' has nonzero value which mean the if-statement is doing : if( (rep =='n') or true) ), so you always got "Exiting program" printed.
you should you if (rep == 'n' || rep =='N')
and the same, your while statement should be while (rep == 'y' || rep == 'Y')
OR
move the
cout << "\n\tExiting program\n";
out your while loop without condition to get it printed only when finish the loop

C++ equality check on char from cin against another char never equates to true??? (No compiler errors)

I'm stuck as to why the condition below isn't triggering when either an 'n' or a 'y' is entered at the console. When executed you can't get out the the if statement, but i know for sure that
!(cin >> again)
isn't the culprit, as that was previously the only condition in the if statement and I was able to skip/enter the if block if a character/numeral was entered, which was as expected. Here is the code:
char again;
while (1) {
cout << endl;
cout << "I see another one, care to shoot again? (y/n): ";
if (!(cin >> again) || (again != 'n') || (again != 'y')) {
// Error checking for numberals & non 'y' or 'n' characters
cout << "Please enter 'y' or 'n' only." << endl;
cin.clear();
cin.ignore(1000, '\n');
continue;
}
break;
}
I'm stumped on this so any help would be hugely appreciated!
if(...|| (again != 'n') || (again != 'y')) {
is faulty logic. What you say is
if "again" is not n or it's not y, then do the following...
now, since "again" can't be n and y at the same time, this always evaluates to true; most probably, even your compiler notices that and just jumps right into your if's content.
What you want is something like
if(!(cin>>again) || ( again != 'n' && again != 'y') {
Because that reads
if cin>>again didn't work or again is neither n nor y then,...

how to only allow 3 values in a "if" and "while" statement to allow the loop to exit

I'm just stuck on some logic statements.
specifically the ones that are in the function char GetInteger() so how would I only allow 3 values to cause the loop to exit.
char GetInteger( /* out */ char& usrinput)
{
do
{
cin >> usrinput;
cin.ignore(200,'\n');
if (usrinput != 0 || usrinput != 1 || usrinput != 2)
{
cout << "Invalid Input." << userinput << " Try Again\n";
}
} while(usrinput != 0 || usrinput != 1 || usrinput != 2);
return userInput;
}
Two issues with this code:
First userinput has a type of char. So when you read from a stream you read a single character (after dropping white space). So when a user types 1<enter> you get the character '1' in the variable userinput. Note the character '1' is not the same as the number 1.
Thus your test should be:
userinput != '1';
Secondly your boolean logic is wrong. When first learning it is sometimes easier to state the problem as a list of values that you would like to be acceptable (not the unacceptable ones).
You want the conditions to be false if the userInput has one of your accepted values (any good value will fail the test and thus not invoke the bad code). The first step to this is to get a true if any of your values are valid.
// If any value is good then true.
userinput == '1' || userinput == '2' || userinput == '3'
To invert this just add a not to the expression.
if (! (userinput == '1' || userinput == '2' || userinput == '3') )
Note: in boolean logic
!(A || B) => (!A && !B)
So you could re-write the above as:
if (userinput != '1' && userinput != '2' && userinput != '3')
I think this was your main mistake you converted the == into != but did not convert the || into &&.
I would also suggest that you could simplify this (as you may get more valid result) byconverting this into a range based test.
if (userinput < '1' || userinput > '3')
{
// Test Failed.
}
Additionally. Since you have the test in two places. You should yank it outinto its own function. Then you can call the function to do the test.
bool isUserInputValid(char userInput)
{
return userInput >= '1' && userInput <= '3';
}
Now we can re-write your original function as:
char GetInteger( /* out */ char& usrinput)
{
do
{
cin >> usrinput;
cin.ignore(200,'\n');
if (!isUserInputValid(userinput))
{
cout << "Invalid Input." << userinput << " Try Again\n";
}
} while(!isUserInputValid(userinput));
return userInput;
}
First of all, you should use int instead of string as you are reading integer.
You can use while(1) instead of putting condition in while. Inside while loop, if your selection is 0 or 1 or 2, you can simply break the loop.

Why does this if statement not behave as I'd expect?

I am making a program that will evaluate the value of something. I have a variable that holds the total value to be added, rcoverE. When I test "y" for the second question, it works, but when I put in "n", it adds 5 anyway. Why is this happening?
#include <iostream>
using namespace std;
int main(){
int year, yearE, rcoverE;
string rcover, func;
cout << "Enter the decade your thing was produced (eg. 20):";
cin >> year;
cout << "Does you typewriter have original thingy? (y,n):";
cin >> rcover;
rcoverE = 0;
if(rcover == "y" || "Y"){
rcoverE = rcoverE + 5;
}else{
rcoverE = rcoverE + 0;
}
cout << rcoverE;
yearE = 100 - year / 2;
}
if(rcover == "y" || "Y"){
This condition is wrong it should be:
if(rcover == "y" || rcover == "Y"){
This: if(rcover == "y" || "Y"){ is logically equivalent to if(rcover == "y" || "Y" != 0) and "Y" != 0 is always true.
if(rcover == "y" || "Y")
Does not evaluate the way you think it does. This actually evaluates as if ("rcover == 'y') or if('Y')", not "rcover == ('y' || 'Y')." In some languages the compiler would not let you do this, but in C++, simply putting in the statement "Y" returns true. You need to change the statement to:
if(rcover == "y" || rcover == "Y")