Why would the statement not work - c++

I am a beginner at c++ programming and I am supposed to create a program in which answers that does not meet certain conditions would produce certain statements.
I also added
cin.ignore(INT_MAX, '\n');
in order to use
getline
and
cin
together. However, I think I may have misunderstood the nature of how they work and I used
cin.ignore(INT_MAX, '\n')
before using the first getline function, and it was causing my program to pause. I think that I am supposed to use this only if i use cin before, and when I want to use a getline function in order to prevent the getline function from taking in the empty space?
at the start, and it is causing me errors, I'm not sure when I use this.
I think this part might be the error... but I'm not quite for how the || and the && operators work
else if (donorGender != "Male" || "Female" || "Trans Male" || "Trans Female" || "Queer" || "Different")
is this it the way I do it?
else if (donorGender != "Male" && donorGender != "Female" && donorGender != "Trans Male" && donorGender != "Trans Female" && donorGender != "Queer" && donorGender != "Different")
or is this the way I do it
Please help...

The statement
cin.ignore(INT_MAX, '\n');
is pausing your program at the start until you press Enter key.
From this:
std::istream::ignore
istream& ignore (streamsize n = 1, int delim = EOF);
Extract and discard characters
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
Generally, cin.ignore(INT_MAX, '\n') used with getline if you have some other input statements using cin before calling getline because when a user inputs something with cin, they hit Enter key and a \n (newline) character gets into the input buffer. Then if your program calling getline, it gets the newline character instead of the string you want. In your program you are is using getline for the first input from the user, so you don't need it. You can safely remove cin.ignore statement from your program.
This statement is wrong:
else if (donorGender != "Male" || "Female" || "Trans Male" || "Trans Female" || "Queer" || "Different")
You need to compare donorGender with all the possible valid values and not only with just one valid value. Even if you compare donorGender != with all valid values this will not work because || operator in the condition will always evaluate to true as a valid value of donorGender will be != rest of all valid values. Change it to:
else if (donorGender != "Male" && donorGender != "Female" && donorGender != "Trans Male" && donorGender != "Trans Female" && donorGender != "Queer" && donorGender != "Different")
With these changes, your program should work as expected.
Also, I would suggest you to add some input validation for all the inputs you are taking from the user.

Your code says that it will test donorName else donorGender and so on. You need to check all the conditions. and your donorGender checking if statement is not correctly formatted. What if user enters both name and gender invalid!
I think you should not check other conditions if one if false. if you want to tell all the wrong things then approach is different. but in your case below code can help. try it out!
Nested Conditional Statements
if(donorName != "")
{
if(donorGender == "Male"
or donorGender == "Female"
or donorGender == "Trans Male"
or donorGender == "Trans Female"
or donorGender == "Queer"
or donorGender =="Different")
{
if(donorAge >= 0) {
if(donorWeight >= 0) {
if (donorHeight >= 0)
{
cout << "--- You must enter a valid height." << endl;
return (-1);
}
else {
}
}
else {
cout << "--- You must enter a valid weight." << endl;
return (-1);
}
}
else {
cout << "--- You must enter a valid age." << endl;
return (-1);
}
}
else {
cout << "--- You must enter a valid gender." << endl;
return(-1);
}
}
else {
cout << " --- You must enter a valid name." << endl;
return (-1);
}

Related

C++ Blackjack code only going to first if statement

I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the user to try again.
I'm still fairly new to C++, so some help would be appreciated.
while (repeat == 0)
{
char hitStand;
cout << "Would you like to HIT or STAND [H/S]";
cin >> hitStand;
if (hitStand = "H" || "h")
{
PcardNew = rand() % 13 + 1;
cout << endl;
cout << "Your new card is: " << PcardNew << endl;
if (PcardNew > 10)
{
PcardNew = 10;
}
playerTotal = playerTotal + PcardNew;
cout << "Your new total is: " << playerTotal << endl;
}
else if (hitStand = "S" || "s")
{
break;
}
else
{
cout << "Please enter a valid imput [H/S]" << endl;
}
}
There are (at least) three errors in the single if (hitStand = "H" || "h") line!
First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator.
Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of characters. Use single quotes for single characters (thus, 'H' and 'h').
Third, you can't compare one object with two others like that with a logical or (||) operator. You need to make two separate comparisons and then or the results of each:
So, use this:
if (hitStand == 'H' || hitStand == 'h')
{
//...
And similarly for your second test:
else if (hitStand == 'S' || hitStand == 's')
{
//...
That is because your condition in if statement is always true. Since "h" is in or (||).
Instead use:
if (hitStand == 'H' || hitStand == 'h')
and
else if (hitStand == 'S' || hitStand =='s')

Input not being read properly by if condition statement

one would think this is easy, but for some odd reason, my conditional statement is ignoring user input.
If I input a character 'N' or 'n' it still executes the 'Y' portion of the conditional statement, have a look:
while (i < 10) {
cout << "Would you like "<< nameOfDish[i] << "? Please enter Y or N.\n";
cin >> userResponse;
if (userResponse == 'y' || 'Y')
{
cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
cin >> quantityOfDish[i];
if (quantityOfDish[i] == 0) {
cout << "I suppose you're entitled to change your mind.\n";
}
else if (quantityOfDish[i] < 0) {
cout << "Your generosity is appreciated but I must decline!\n";
quantityOfDish[i] = 0;
}
i++;
}
else if (userResponse == 'n' || 'N')
{
i++;
}
else
{
cout << "I think you mumbled NO, so I'll just go on.\n";
i++;
}
}
Is there any particular reason why despite inputting 'n' it still goes into the 'Y' if conditional block?
I have stepped through the code in the debugger, and I noticed that the userResponse variable is being read in properly. Yet, the if condition does not seem to be working properly. Thanks!
This statement (and your other if statement) is not doing what you think it does:
if (userResponse == 'n' || 'N')
Try this instead:
if (userResponse == 'n' || userResponse =='N')
You need to define each logical operation individually in a condition check. You will have to compare userResponse with n and N separately.
if (userResponse == 'y' || userResponse == 'Y')
{
cout << "How many orders of " << nameOfDish[i] << " would you like?\n";
cin >> quantityOfDish[i];
if (quantityOfDish[i] == 0) {
cout << "I suppose you're entitled to change your mind.\n";
}
else if (quantityOfDish[i] < 0) {
cout << "Your generosity is appreciated but I must decline!\n";
quantityOfDish[i] = 0;
}
i++;
}
It's been awhile since I worked in C++, but I'm fairly sure I know what's going on.
The || operator does not work on a single conditional, there must be two complete conditionals, one on each side. Try replacing your if statement with this line:
if (userResponse == 'y' || userResponse == 'Y')
Maybe you are used to SQL? You need to repeat the userResponse
if userResponse == 'n' || userResponse == 'N'
Otherwise you are actually testing
if userResponse is 'n' or the char'N' exists
The error in this code is, as others have pointed out, the if statement. However, I feel this may need some clarification. Every C++ expression returns a value. For example.
userResponse == 'y'
returns the value 1 if userResponse is 'y' and 0 if it is anything else. The operator || returns 1 if either the left or the right expression is non-zero.
Finally, the if statement checks to see whether or not the expression is zero or non-zero. So,
if (5)
cout << "X";
else
cout << "Y";
will print X and
if (0)
cout << "A";
else
cout << "B";
will print B.
Now, we can begin to understand why your code compiled successfully, but didn't do what you wanted it to.
if (userResponse == 'y' || 'Y')
In this example, the || operator will always return 1 because the expression on the right, 'Y', will always be non-zero (specifically, it will be 89, since C++ characters are just aliases for their ASCII corresponding number). And of course,
if (userResponse == 'y' || userResponse == 'Y')
work as intended. But there is a much better solution and that would be the switch statement, whose purpose is to handle situations like this. Here it is in action:
switch (userResponse) {
case 'y':
case 'Y':
//The user answered yes, handle that situation here.
break;
case 'n':
case 'N':
//The user answered no, handle that situation here.
break;
default:
// The user did not enter a valid answer,
// handle that situation here.
break;
}

Endless loop, can't find error

I'm making a small program for myself and any of my friends at school to use. I have a function (C++), called getChoice(), that returns a choice that the user made:
std::string getChoice(const std::string& s)
{
std::string choice;
if (s == "sp")
{
do
{
std::cout << "Do you want to search for a video or play it? (s/p): ";
std::cin >> choice;
if (choice[0] == 'S' || choice[0] == 'P')
choice[0] = tolower(choice[0]);
} while (choice.compare("s") != 0 || choice.compare("p") != 0);
}
else if (s == "vidtype")
{
do
{
std::cout << "Do you want to use vine or yt? (vine/yt): ";
std::cin >> choice;
} while (choice.compare("vine") != 0 || choice.compare("yt") != 0);
}
else
{
std::cout << "Uh, this function only supports \"sp\" and \"vidtype\"\n\n";
exit(EXIT_FAILURE);
}
return choice;
}
My issue is that the program gets stuck in an infinite loop at
"Do you want to search for a video or play it? (s/p): ";
I've rewritten the entire program, and that didn't fix it. I've looked up on using !=; it seems that I should use std::string.compare().
And I also tried outputting choice after using std::cin. It looks just fine in console output, showing s and p, but the tests in the do-while both fail somehow. Is there something I'm missing here?
while (choice.compare("s") != 0 || choice.compare("p") != 0);
If not S or not P:
If you input S, not P will evaluate to true, this continuing the loops
If you input P, not S will evaluate to true, this continuing the loops
If you input anything other than S or P, both will be true, this continuing the loop.
You probably meant to do:
while (choice.compare("s") != 0 && choice.compare("p") != 0);
If not S and not P (aka some other character besides S and P).
This incorrect logic is also present in your second loop (thank you dwcanillas)
while (choice.compare("vine") != 0 || choice.compare("yt") != 0);
Change the condition in the while loop the following way
do
{
std::cout << "Do you want to search for a video or play it? (s/p): ";
std::cin >> choice;
if (choice[0] == 'S' || choice[0] == 'P')
choice[0] = tolower(choice[0]);
} while (choice.compare("s") != 0 && choice.compare("p") != 0);
It is easier to consider the negation of the condition when the loop has to be terminated. For example
!(choice.compare("s") != 0 && choice.compare("p") != 0)
or more visually
not (choice.compare("s") != 0 && choice.compare("p") != 0)
is equivalent to
choice.compare("s") == 0 || choice.compare("p") == 0
So when the user entered either "s" or "p" then exit the loop.
The problem is the line
while (choice.compare("s") != 0 || choice.compare("p") != 0);
If you change the logic to
while (choice.compare("s") == 0 || choice.compare("p") == 0);
it will be good.

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.