how to compare string to multiple char c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to find out whether a string has words in it
if( mystring[i] == 'a' | 'b' | 'c' | 'd' | 'e' |)
// do stuff but it always does stuff no matter that mystring[i] is.
is always evaluating to true even if mystring[i] = a space or a period
I tried to use strcmp but I couldn't get that working right. I want it to evaluate true
only if it = a letter.

You cannot compare multiple values like that. Use a switch statement instead:
switch( mystring[i] )
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
{
// do something
break;
}
default:
{
// do something else
break;
}
}
In C/C++, if a case block does not have a break then its execution will continue in the next case block. Thus, all 5 values will execute the same // do something code. Some languages do not do that.
Another option, only because your values are consecutive, is to use this:
char ch = mystring[i];
if( (ch >= 'a') && (ch <= 'e') )
{
// do something
}
else
{
// do something else
}

There are two issues in your code. First, due to precedence, your expression is being evaluated as:
(mystring[i] == 'a') | ('b') | ('c') | ('d') | ('e')
Second you are using bitwise-or instead of logical-or. What you want to do is have a full condition as each term and switch to logical or:
char c = mystring[i];
if (c == 'a' || c == 'b' || c == 'c' ...)
Finally, if you are planning to check for every lower case letter, the standard library has an islower method which can check that:
if (islower(mystring[i])

Related

Rewriting an if statement to make it more condensed and cleaner [duplicate]

This question already has answers here:
Concise way to say equal to set of values in C++
(5 answers)
Closed 6 years ago.
I am working on a school assignment. What I want to do is not the focus of the assignment, merely something I would like to do better.
I have the following if statement where equation is a string
if( (equation[0]== "*") || (equation[0]== "/") || (equation[0]== "+") || (equation[0]== "-"))
All it does is check to see if the first and last characters of the string are one of 4 operators. This is long, bulky, and hopefully not the best way of doing this. Sadly I do not have access to regular expressions as this type of check would be very easy using them.
Is there a better way of writing the if statement without using regular expressions? Something along the lines of
if( equation[0] == ("/" || "*" || "+" || "-"))
How about
if(std::string("*/+-").find(equation[0])!=std::string::npos)
You may consider using switch operator
switch(equation[0]) {
case '/':
case '*':
case '+':
case '-':
//your code
break;
default:
//else statement
}
I don't think it is possible to do what you're asking.
Best you can do is put equation[0] in another shorter name variable.
std::string a = equation[0];
if( (a"*") || (a== "/") || (a== "+") || (a== "-"))
No, that's not possible. But I think it's always cleaner and more readable to
switch (equation[0]) {
case '*':
case '/':
case '+':
case '-':
//dostuff
break;
default:
//dostuff
}
This way, it's also really easy to replace (add or remove) new characters. If you would to it with a regular expression, that would be definetely more work to do.

How to do input validation simply in C++?

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

I working on this C++ code and can't get it to work...see below [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Can't get this to work...roadblock....help?!? I am new to this and am trying to write game code for a C++ course at Delco CC. Any help would be appreciated greatly. When it runs it will not loop as intented and thus I'm stuck from moving forward in coding the rest of my game.
#include<iostream>
#include<string>
using namespace std;
int findMap()
{
int space;
cout<<"| 1 | 2 | 3 |"<<endl;
cout<<"|_____|_____|_____|"<<endl;
cout<<"| 4 | 5 | 6 |"<<endl;
cout<<"|_____|_____|_____|"<<endl;
cout<<"| 7 | 8 | 9 |"<<endl;
cout<<"| | | |"<<endl;
cout<<"What space is your map in?"<<endl;
cin>> space;
if (space == 4||8)
{
cout<<"Nope! There's nothing in here."<<endl;
return findMap;
}
if (space == 5||6)
{
cout<<"Tough luck, you only found blank map paper. It's
useless."<<endl
return findMap;
}
if (space == 1||7)
{
cout<<"You found poision gas. You failed."<<endl;
return 0;
}
if (space == 1)
{
cout<<"Yippie! You found your map!"<<endl;
}
if (space == 9)
{
cout<<"Well, you found your wallet..."<<endl;
return findMap;
}
}
int game(findMap)
{
string name;
int findMap;
cout<<"It appears that you have been lost at sea."<<endl;
cout<<"But don't worry, you'll only have to survive until you reach
land, for this round."<<endl;
cout<<"Anyways, why don't you tell me your name?"<<endl;
cin>> name;
cout<<"Well, "<< name<<", do yourself a favour and find your
map..."<<endl;
cout<<findMap<<endl;
}
Such the classic defect typo.
The logical OR is specified as:
if ((space == 1) || (space ==7))
This has to do with the order of evaluations semantics.
Edit 1: Why your version isn't working correctly
In the expression:
(space == 1 || 7)
The phrase 1||7 is evaluated first to a true condition.
The expression now is:
(space == true)
The identifier true has type bool, so it is converted to the same type as space, which is int. The int representation of true is 1.
Substituting gives us:
(space == 1)
You were kind of lucky with this one, but the case for 7 doesn't exist. All of your if statements are evaluated the same way.
This is a common misconception in c++. The or (||) operator is usually used in boolean values. Thus when you check (space == 1||7) it first evaluates space == 1 which would evaluate to true if and only if space is equal to 1. Then after it evaluates (space == 1) it applies the or operator on 7. Since 7 always evaluates to true (space == 1||7) always evaluates to true because the or operator evaluates to true if any part in the expression evaluates to true.
What you want is (space == 1 || space == 7) because it will evaluate the first, then the second sub expression (i.e. space == 1, then space == 7) and return true if and only if either of them evaluated to true.

Boolean and logical operators using characters, combining multiple tests [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm having an issue with boolean and logical operators. I'm trying to get wantsToppings to evaluate to true if toppings equals 'T' or 't', but this code evaluates to true, regardless of user input. I'm not sure what I am missing, but I know I gotta be missing something.
Thanks for any help.
cout << "Toppings wanted (T for toppings/N for no toppings)? ";
cin >> toppings;
if (toppings == 't' || 'T'){
wantsToppings = true;
} else {
wantsToppings = false;
}
You are missing how logical operators work. Here is what you do:
if (toppings =='t' || 'T')
and here is how it's done:
if (toppings =='t' || toppings == 'T')
You don't really need the complexity of the if either, it could just be:
wantsToppings = (toppings == 't' || toppings == 'T');
The expression
if (toppings == 't' || 'T')
does not mean to toppings is either of 't' or 'T', but rather essentially (it's in fact a little bit more complicated than this once you factor in lazy evaluation):
evaluates each sub-expression (the expression toppings == 't' and the expression 'T')
convert results of those expressions to boolean values if required
perform the logical or (||) of the above boolean values
Now 'T' is a char which gets promoted to the boolean value true, hence the result is always true.
As others have pointed out, the expression you are looking for is
if (toppings == 't' || toppings == 'T')

Using of arithmetic and logical operators in switch statement [duplicate]

This question already has answers here:
Switch with range of values
(3 answers)
Closed 9 years ago.
I want to use logical operators in switch statment.
For Example:
" x is greater than 3 and is less than 7 "
Using it in If statement.
if(x > 3 && x < 7)
{
//something
}else if(x 11 3 && x < 15){
// anything
}
How can I use it in switch statement.
And how to use arithmetic operators.
UPDATE
Now how we use it in switch. Can there is not way to use it in switch.
You mean, something like this?
switch (some_var)
{ case 4 : // fall through
case 5 : // fall through
case 6 : do_something();
break;
default : do_something_else();
break;
}
It's ugly, and gets worse the larger a range you want to cover, but since switch cases must be constants, that's one way to do it.
Another way would be:
switch ((some_var > 3) && (some_var < 7))
{ case 0: do_something_else(); break;
default: do_something(); break;
}
But that'll only work if you have exactly one range you want to test. There are other ways if you have a set of equally-sized intervals that are spaced equally far apart, using some basic arithmetic, but we'd have to know a bit more about the specific problem(s) you're trying to solve...
Frankly, though, I think the if construct is the better solution...