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.
Related
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')).
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,...
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.
I have an assignment for my Intro to Comp Sci course at college. We are told to use only Loops & Boolean Expressions to create the program.
Here is a link to the assignment sheet directly:
http://cs.saddleback.edu/michele/Teaching/CS1A/Assignments/AS8%20-%20Boolean%20Expressions.pdf
I got it working with a bunch of If, Then, Else statements until I read the directions again and had to change it.
I got the 'm' 'f' 'M' 'F' part to work, but I can not get the heightOK or the weightOK (directions #2 and #3) to work out.
Please help, thanks!
PS I am brand new to programming...
Here is what I have so far: `
char gender;
int weight;
int height;
bool heightOK;
bool weightOK;
cout << "Please enter the candidate’s information (enter ‘X’ to exit).";
cout << "Gender: ";
cin.get(gender);
cin.getline(100 , '\n');
if (gender == 'm' || 'M' || 'f' || 'F')
{
}
else
{
cout << "***** Invalid gender; please enter M or F *****";
}
cout << "Height: ";
cin >> height;
cout << "Weight: ";
cin >> weight;`
You can do this without if statements. You should use do-while loops for each input, such that you loop while the input is invalid. Then, you can set your bool variables like this:
heightOK = ((gender == 'm' || gender == 'M') &&
(height > MALE_TOO_SHORT && height < MALE_TOO_TALL));
heightOK = (heightOK || (/*same as above, female version*/));
You could do that all in one line, but that gets hard to read, IMO. You should be able to set weightOK the same way.
EDIT: The do-while loop asks for and gets the input. Then, the while statement tests the input for validity.
do {
cout << "enter gender (m/f)";
cin >> gender;
} while ( !(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') );
If you want to tell the user that the input is invalid, you can use a while loop after getting the input the first time.
Here's the expression showing that the ternary operator is a valid Boolean function with respect to
(p ∧ q) ∨ (¬p ∧ r)
"(p and q) or ((not p) and r))" or "if p then q, else r"
See also: http://en.wikipedia.org/wiki/%3F:, http://en.wikipedia.org/wiki/Conditioned_disjunction
Full disclosure, I didn't read the assignment. I just saw the implication in your post that you're restricted from using "if then else" statements and thought I'd offer a creative way to cheat.
/*
PROGRAM: Ch6_14.cpp
Written by Corey Starbird
This program calculates the balance
owed to a hospital for a patient.
Last modified: 10/28/13
*/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
// Prototypes for In-patient and Out-patient functions.
double stayTotal (int, double, double, double); // For In-patients
double stayTotal (double, double); // For Out-patients
int main()
{
char patientType; // In-patient (I or i) or Out-patient (O or o)
double rate, // Daily rate for the In-patient stay
servCharge, // Service charge for the stay
medCharge, // Medication charge for the stay
inTotal, // Total for the In-patient stay
outTotal; // Total for the Out-patient stay
int days; // Number of days for the In-patient stay
// Find out if they were an In-patient or an Out-patient
cout << "Welcome, please enter (I) for an In-patient or (O) for an Out-patient:" << endl;
cin >> patientType;
while (patientType != 'I' || 'i' || 'O' || 'o')
{
cout << "Invalid entry. Please enter either (I) for an In-patient or (O) for an Out-patient:" << endl;
cin >> patientType;
}
cout << "FIN";
return 0;
}
Hey, brand new to C++ here. I am working on a project and I'm having trouble figuring out why my validation for patientTypeisn't working properly. I first had double quotes, but realized that would denote strings. I changed them to single quotes, my program will compile and run now, but the while loop runs no matter what I enter, I, i, O, o, or anything else.
I don't know why the while loop isn't checking the condition, seeing that I did enter one of the characters in the condition, and move on to cout. Probably a simple mistake, but I thank you in advance.
Your while condition is wrong.
You most likely want this:
while (patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')
You got to use &&. patientType isn't I or it isn't i would be always true. Also you got to use patientType != for every item being checked or the characters i, o, O would be implicitly converted to bool (true for all of them).
while (patientType != 'I' && patientType != 'i' &&
patientType != 'O' && patientType != 'o')
As written, the condition is always true, because three of the four expressions OR-ed together are non-zero.
The problem is this line
(patientType != 'I' || 'i' || 'O' || 'o')
This doesn't do what you think, you want
(patientType != 'I' && patientType != 'i' && patientType != 'O' && patientType != 'o')
The comparison operators are strictly between two values, the left and right side.
C and C++ treat any value that is not zero as being "true". So,
(patientType != 'I' || 'i' || 'O' || 'o')
Was being translated as
(patientType != 'I') or ('i' is not 0) or ('O' is not 0) or ('o' is not 0)