C++ do/while loop with two different conditions - c++

I want the do while loop to check to see if the entered input is R OR P. I think it is checking for both and when I get to that part when I run, it pauses for a minute and then I get "CPU Limit Exceeded (core dumped). On another related note, am I in danger of breaking something?
/************************************************/
/* Name: servcode */
/* Description: Get service type */
/* Parameters: N/A */
/* Return Value: servcode */
/************************************************/
char servcode()
{
char servcode = 'a'; // Define variable for service code
char serviceyn = 'n'; // Define variable for user verify
int i = 1; // Define variable for sentinel loop
do {
cout << "\n" << "\n" << "Please enter your service code, [R]egular or [P]remium: " << "\n";
cin >> servcode;
while ((servcode != 'R', 'P') && (i < 3));
{
cout << "\n" << "Error - invalid service code, please try again.";
cout << "\n" << "Please enter your service code: ";
cin >> servcode;
i++;
if (i == 3)
{
cout << "\n" << "Too many invalid attempts, program terminating." << "\n"
<< "Have a nice day. " << "\n" << "\n";
exit (0);
} //end if
} //end while
cout << "\n" << "You entered: " << servcode << "\n"
<< "Is that correct? [y,n]";
cin >> serviceyn;
} while (serviceyn != 'y'); // end do/while loop
return servcode;
}

The correct syntax is:
while (servcode != 'R' && servcode != 'P' && i < 3)
Note the expanded comparison and the removal of the semicolon at the end:
(servcode != 'R', 'P') is valid C++ but doesn't do what you're expecting it to do;
the semicolon makes the statement into a loop with an empty body, so it continues executing forever since the loop condition never changes.

Change:
while ((servcode != 'R', 'P') && (i < 3));
to:
while ((servcode != 'R') && (servcode != 'P') && (i < 3))
Note the removal of an unwanted semicolon.

You need to do something like this:
while(something != 'a' && something != 'b')
You're using the comma operator, which discards the results of every expression except the last, so this:
while(something != 'a', 'b')
Will compare something with a, ignore the result, and use 'b' as the condition of the loop. 'b' is a non-zero value, so it's always true and the loop goes on forever (or until memory runs out, or something else stops it).

(servcode != 'R', 'P')
Should be:
(servcode != 'R') && (servcode != 'P')
Kudos to PaulR for correction. My brain is not in gear.

Let's break down this statement and see what it's doing. I've put in some extra punctuation that does not change the meaning of the statement.
while (((servcode != 'R'), ('P')) && (i < 3)) { };
The comma operator separates two different expressions and returns the value of the second one. The first part probably does what you expect, but the second part is just a literal character 'P' which is always true!
The semicolon at the end of the statement marks the body of what will be executed as the while loop. It's a do-nothing which does not change the value of servcode or i, so obviously once you enter the loop you will never leave it. This is a common mistake.

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;
}

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,...

C++ Checking Against Particular Numbers

Hello Dear Programmers,
I've been working on a piece of code for a while, but I don't seem to figure this out, i'm trying so hard to check an input with a specific number, but so far it ends up not working and even when number 2,3, or 4 is pressed the error message pops up, and I go to my if else condition. here are the codes, number_of_bedrooms is an integer.
out << "Number Of Bedrooms: (Limited To 2,3, and 4 Only)" << endl;
if (isNumber(number_of_bedrooms) == false ) {
cout << "Please Do Enter Numbers Only" << endl;
cin.clear();
}
else if (number_of_bedrooms != '2' || number_of_bedrooms != '3' || number_of_bedrooms != '4') {
cout << "Numbers Are Only Limited To 2,3, And 4" << endl;
cin.clear();
}
and the function :
bool isNumber(int a)
{
if (std::cin >> a)
{
return true;
}
else
{
return false;
}
}
the first validation which checks for numbers works fine, but the second validation no, my guess is the system is not capturing inputted data after that boolean function. And if that's the reason, what's the solution ?!!
Change your || to &&, also you need to compare to int not char
else if (number_of_bedrooms != 2 && number_of_bedrooms != 3 && number_of_bedrooms != 4)
Note that a more general way to solve such a problem (for example if your list got much longer) would be to do something like
std::set<int> const allowableBedrooms = {2,3,4};
else if (allowableBedrooms.find(number_of_bedrooms) == allowableBedrooms.end())
{
// Warn user here
}
As your goal conditions are sequential, I'd use something like this:
else if ( number_of_bedrooms < 2 || number_of_bedrooms > 4 ) {
cout << "Numbers Are Only Limited To 2,3, And 4" << endl;
cin.clear();
}
This is very clear and easy to manage if you want to change it. If you want to enumerate everything you'll need to use && instead of || since your want it to both be not 2 and not 3 and not 4 to trigger the issue.
Another problem in your code is that you're comparing against characters by putting the numbers in single quotes. Since these are integers you should not have them in quotations.
You have to change your function to make the change out of the local function like this:
bool isNumber(int * a)
{
if (std::cin >> * a)
{
return true;
}
else
{
return false;
}
}
And then call the function with the address of number_of_bedrooms like this:
out << "Number Of Bedrooms: (Limited To 2,3, and 4 Only)" << endl;
if (isNumber(&number_of_bedrooms) == false ) {
cout << "Please Do Enter Numbers Only" << endl;
cin.clear();
}
else if (number_of_bedrooms < 2 || number_of_bedrooms > 4) {
cout << "Numbers Are Only Limited To 2,3, And 4" << endl;
cin.clear();
}
Check the code above becouse i took off the '' that means you are comparing number_of_bedrooms (int) with '2' (char) so it will be always true.
The condition i wrote would be better then becouse you are considering an interval of numbers, if you are considering the specific numbers you can leave your condition but you should change the logical operator in && and chain with the other != conditions

using user input such as YES and NO to control program flow in C++

I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No = "NO";
if (input == no)
{
cout << "testone" << endl;
}
if (input == yes)
{
cout << "test two" << endl;
//the rest of the program goes here i guess?
}
else
{
cout << "you entered the wrong thing, start again" << endl;
//maybe some type of loop structure to go back
}
but I can't seem to get any variations of this to work, i could make the user type a 0 or 1 instead but that seems really stupid, i'd rather it be as natural as possible, users don't speak numbers do they?
also i need to be able to simply add more words, for example "no NO No noo no n" all would have to mean no
hopefully that makes some sense
also i would love to make this using a window but i've only learned basic c++ so far not even that and i cant find any good resources online about basic windows programming.
You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type in "NO" then it will still go into that last else block.
First of all, input must be std::string, not int.
Also, you've written yes and no wrong:
v
if (input == No)
// ..
// v
else if (input == Yes)
^^^^
If you want your program to work with "no no no ..", you could use std::string::find:
if( std::string::npos != input.find( "no" ) )
// ..
The same with "Yes".
Also, you could do this to be almost case-insensitive - transform the input to upper-case letters (or lower, whatever ), and then use find.This way, yEs will be still a valid answer.
bool yesno(char const* prompt, bool default_yes=true) {
using namespace std;
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
}
string line;
if (!getline(cin, line)) {
throw std::runtime_error("yesno: unexpected input error");
}
else if (line.size() == 0) {
return default_yes;
}
else {
return line[0] == 'Y' || line[0] == 'y';
}
}
string input;
cin >> input;
if (input == "yes"){
}
else if (input == "no"{
}
else {
//blah
}