I want to give an error message if the input is neither character c nor h but I can't get it to work! I looked up some other answers but they mostly use throw/catch method which I didn't understand at all. I just started programming and error handling is in Chapter 20 or 21. Help me out with the most simple way as possible.
This is what I've tried:
cout << "Enter 'c'(even) or 'h'(odd): ";
cin >> your_guess;
if((your_guess != ('c' || 'h')) == false) {
cout << "Wrong Input. Game is restarting... " << endl;
// restart the game ...
}
But it always says Wrong Input. ....
(your_guess != ('c' || 'h')) == false
is wrong. ('c' || 'h') simply evaluates to true. The built-in operator|| takes two bool arguments:
bool operator||(bool, bool)
And since 'c' and 'h' are both not NUL characters, they convert to true.true OR true is true. The language doesn't create some magical entity with which you can do operator==/operator!= with char to see if the character is among those you've listed.
Then, later the bool and char are promoted to int to do the inequality check. I'd guess your_guess won't be equal to 1. And I don't mean '1' (ASCII 49), but 1 (ASCII 1). So you've effectively written if(true)...
What you meant to say is:
(your_guess != 'c' || your_guess != 'h') == false
or
!(your_guess != 'c' || your_guess != 'h')
or
your_guess == 'c' && your_guess == 'h' // your_guess equal 'c' and 'h' at once?
and now you see that there's something wrong with the logic.
The right code for the condition is one of these:
your_guess != 'c' && your_guess != 'h'
!(your_guess == 'c' || your_guess == 'h')
It's just De Morgan's laws all around.
How to do input validation simply in C++?
If the above is not simple for you, you can use switch (because you're probably going to use it anyway). But each case tests variable against compile-time constant.
If the letters you want to check for are stored in a variable, I suggest this:
std::string valid_characters = "ch"; // this will be our "magical entity"
if(valid_characters.find(your_guess) == std::string::npos)
{
// you have entered a character that is not 'c' nor 'h'
}
You can try
switch(your_guess){
case 'c' :
case 'h' :
// do something
break;
default :
cout<<"invalid Input"<<endl;
break;
}
If you are doing an error message in c++, using cerr instead of cout might be something you may want to think about doing in addition to the changing:
your_guess!=('c'||'h'))==false
To one of the correct forms listed in the other answers
Related
I am creating a tic tac toe program in c++ and am almost finished with it, the issue I'm having is when the game needs to end in a tie. I created an if-statement to check when specific combinations are selected and it finds it true even when only one condition is met.
Here is the code...
//takes the users selections and sees if all spots are filled in without a match.
if((b1== "O" || "X") && (b2 == "O" || "X") && (b3 == "O" || "X")){
cout << "The game ended in a tie.";
// Flip = 3 ends the game in a tie.
flip = 3;
}
ex... the game ends in a tie when i change `b1` to and `"O"` or an `"X"` even though `b2` and `b3` are still empty.
The condition:
b1== "O" || "X"
evaluates as:
(b1=="O") || "X"
which is always true. You probably want:
(b1=="O" || b1=="X")
I have a problem i cannot figure out at all!
in my program the user enters numbers to be sorted. i had to be able to sort infinity, negative infinity and the so called "Nullity" (these i defined early in the program)
if the user wants to enter infinity for example they have to enter "Pinf" into the string.
my issue is i store the users input in a std::string and then check if the string is "pinf" or "Pinf" even tho i have entered the number 3 so the string is "3", it still goes into the if statement, what have i done wrong?!
My code is below;
string Temp;
cin>> Temp;
if (Temp.find("Pinf")||Temp.find("pinf")) {
Num = Pinfinity;
}
It thinks the if statement is true everytime.
1.Error - you are using | instead of ||.
2.Error - findreturns
The position of the first character of the first match. If no matches
were found, the function returns string::npos.
You should change
if (Temp.find("Pinf")|Temp.find("pinf")) {
to
if ((Temp.find("Pinf") != string::npos) || (Temp.find("pinf") != string::npos)) {
If you are just searching for Pinf or pinf then you can use this. Note the logical or operator is ||.
if (Temp == "Pinf" || Temp == "pinf") {
| is a bitwise or operator. Use || in place of |
if ( Temp.find("Pinf") != npos || Temp.find("pinf") != npos )
I was wondering if there was a shorter way to write
if (test != 'e' || test != 'd')
I want to write it like
if (test != ('e' || 'd'))
Or something like this so i don't have to repeat "test !="
Thanks
That's the syntax of the language. There's not much you can do about it... If you don't like the way it looks, you can make a boolean function that contains the tests and then just call that function:
bool isEOrD(char test)
{
return (test != 'e' || test != 'd')
}
...
if (isEOrD(test))
EDIT: There are other ways to write this code (see the comments to this answer), but your original way is probably the cleanest approach.
You could use the old C function strchr:
if (!strchr("de", test))
{
// test is not 'd' or 'e'
}
But I don't know whether it is any nicer to look at… personally I would probably just have the two !=.
C or C++ must evaluate the expressions you write in the syntax of the language. The expression ('e' or 'd') always returns true because the 'or-ing' is done by comparing the bits of the values which will never be the same. How is the compiler to know what you want since in C/C++ a raw character is simply an interpretation of an integer. That's why you can legally write:
char aChar = 'a';
// or
char aChar = 0x41; // hex 41 = ascii 'a'
and have them both work.
Sorry, I realized that I put in all of my code in this question. All of my code equals most of the answer for this particular problem for other students, which was idiotic.
Here's the basic gist of the problem I put:
I needed to recognize single digit numbers in a regular mathematical expression (such as 5 + 6) as well as double digit (such as 56 + 78). The mathematical expressions could also be displayed as 56+78 (no spaces) or 56 +78 and so on.
The actual problem was that I was reading in the expression as 5 6 + 7 8 no matter what the input was.
Thanks and sorry that I pretty much deleted this question, but my goal is not to give answers out for homework problems.
Jesse Smothermon
The problem really consists of two parts: lexing the input (turning the sequence of characters into a sequence of "tokens") and evaluating the expression. If you do these two tasks separately, it should be much easier.
First, read in the input and convert it into a sequence of tokens, where each token is an operator (+, -, etc.) or an operand (42, etc.).
Then, perform the infix-to-postfix conversion on this sequence of tokens. A "Token" type doesn't have to be anything fancy, it can be as simple as:
struct Token {
enum Type { Operand, Operator };
enum OperatorType { Plus, Minus };
Type type_;
OperatorType operatorType_; // only valid if type_ == Operator
int operand_; // only valid if type_ == Operand
};
First, it helps to move such ifs like this
userInput[i] != '+' || userInput[i] != '-' || userInput[i] != '*' || userInput[i] != '/' || userInput[i] != '^' || userInput[i] != ' ' && i < userInput.length()
into its own function, just for the clarity.
bool isOperator(char c){
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
Also, no need to check that it's no operator, just check that the input is a number:
bool isNum(char c){
return '0' <= c && c <= '9';
}
Another thing, with the long chain above, you got the problem that you will also enter the tempNumber += ... block, if the input character is anyhing other than '+'. You would have to check with &&, or better with the function above:
if (isNum(userInput[iterator])){
tempNumber += userInput[iterator];
}
This will also rule out any invalid input like b, X and the likes.
Then, for your problem with double digit numbers:
The problem is, that you always input a space after inserting the tempNumber. You only need to do that, if the digit sequence is finished. To fix that, just modify the end of your long if-else if chain:
// ... operator stuff
} else {
postfixExpression << tempNumber;
// peek if the next character is also a digit, if not insert a space
// also, if the current character is the last in the sequence, there can be no next digit
if (iterator == userInput.lenght()-1 || !isNum(userInput[iterator+1])){
postfixExpression << ' ';
}
}
This should do the job of giving the correct representation from 56 + 78 --> 56 78 +. Please tell me if there's anything wrong. :)
#include<iostream>
using namespace std;
int main()
{
char again;
do
{
cout<<"you are in the while loop";
cout<<"do you want to continue looping?";
cin>>again;
} while (again != 'n' || again != 'N');
system("pause");
return 0;
}
i know something is wrong with the test condition in the 'while'. But I can't figure it out.
when the input of the user is neither 'n' nor 'N', the loop should keep on printing the code "you are in the while loop". Once 'n' or 'N' is pressed, the program will be terminated.
However for my code, program will keep on looping the code regardless what character i enter.
But when i change the '||' to '&&', the program can ran as desired.
Anyone can tell me what is going on?
This is a common boolean logic question. || means "or," which means "as long as one side of this is true, then the expression is true." So when you pass an uppercase 'N' to c != 'n' || c != 'N' the program says "well, 'N' is not equal to 'n', therefore one side of the expression is true, therefore the whole expression is true and there is no need to check the rest of the expression." Even when you press lowercase 'n', the program says "well, 'n' is equal to 'n', but it's not equal to 'N', therefore one side of the expression is true, therefore the whole expression is true." This is what is happening in your while loop.
On the other hand, && means "and" which means "both sides of the expression must be true"; when you pass an uppercase 'N' to c != 'n' && c != 'N' the program thinks "'N' is not equal to 'n', but it is equal to 'N', therefore only one side of the expression is true, therefore the expression is false."
This gets confusing because if you were testing to see if the characters entered were equal to particular values you would use || (e.g., "I want to know if 'a' or 'b' or 'c' was entered").
Basically, when you would use || for a particular expression, and you want the opposite of that expression then you need to change to && (e.g., I want none of 'a', 'b' or 'c'; or to put it another way, the value cannot be 'a' and it cannot be 'b', and it cannot be 'c'"). Likewise, if you would use && for a particular expression, and you want the opposite of that expression then you need to use ||. This is one of De Morgan's laws, which I would recommend you read up on so you can avoid having to rediscover each of them on your own.
Yes: || is "or" and && is "and".
Every character is either "not 'n'" or "not 'N'" because it can't possibly be both 'n' and 'N' simultaneously.
Another (probably simpler to read) way of writing the condition would be:
!(again == 'n' || again == 'N')
which means "the opposite of (again is either 'n' or 'N')".
It is the boolean algebra called "De Morgan's laws".
Not (P And Q) = (Not P) Or (Not Q)
Not (P Or Q) = (Not P) And (Not Q)
In your case, you want users not to enter 'n' or 'N', it can be translate in to this logic.
!(again == 'n' || again == 'N')
When applying De Morgan's laws, it will be
(again != 'n' && again != 'N')
For more info, you might want to read Propositional logic
Although the original poster is happy now, I didn't see this in the other answers:
(true && true ) == true
(true && false) == false
(false && true ) == false
(false && false) == false
(true || true ) == true
(true || false) == true
(false || true ) == true
(false || false) == false
!true == false
!false == true
That's everything!
I understand your problem well,and here is the explanation:
The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while.
in your code,when you press'n' or'N',your test condition will be always one true and one false,
so when you use || you will satisfy the test condition (true||false=true) ,so the program will execute the body of the loop again.
but when you use && ,this will gives (true && false =false),the test condition is not statisfied anymore,so the program will not execute the body of the loop again.
I hope that's helpful.....enjoy programing!
Ameraradi
&& is a logical AND.
|| is a logical OR.
(also, & is a bitwise AND, and | is a bitwise OR.)
you might want to try while(!(again == 'n' || again == 'N'))