Checking what type each character in a string is - c++

I have a function that I'm using to try to check whether a string is in the correct format. I'm trying to do that by looking at each character and determining if it is of the correct type. However no matter what I try I get an error that I cannot figure out. The code is below:
bool valid(string checkcode)
{
if(checkcode.length()!=6) return false;
else if(isalpha(checkcode.at(0)))&(isalpha(checkcode.at(1)))&(isdigit(checkcode.at(2)))&(isdigit(checkcode.at(3)))&(isalpha(checkcode.at(4)))&(isalpha(checkcode.at(5))) return true;
else return false;
}
The error I'm getting is at the first '&' and it says "Error: expression must be an Ivalue or function designator" I'm really stuck here, any help is appreciated.

isalpha(checkcode.at(0)))&(isalpha(checkcode.at(1)))
//bit and
should be
isalpha(checkcode.at(0)))&&(isalpha(checkcode.at(1)))
//^^logical and
You need to use logical and in this case.
You also need to make sure that your parentheses match.
//better to format multiple conditions and make sure () match
if(
(isalpha(checkcode.at(0)))
&&(isalpha(checkcode.at(1)))
&&(isdigit(checkcode.at(2)))
&&(isdigit(checkcode.at(3)))
&&(isalpha(checkcode.at(4)))
&&(isalpha(checkcode.at(5)))
)
return true;

bool valid(string checkcode)
{
return checkcode.length() == 6
&& (isalpha(checkcode.at(0)))
&& (isalpha(checkcode.at(1)))
&& (isdigit(checkcode.at(2)))
&& (isdigit(checkcode.at(3)))
&& (isalpha(checkcode.at(4)))
&& (isalpha(checkcode.at(5)));
}

The reason for your error is that your parentheses are in the wrong places. The & that the compiler complains about is outside the conditional expression of the if statement.
The compiler sees this as the condition to be tested:
if(isalpha(checkcode.at(0)))
The remaining part is considered the statement to execute when the condition is true:
&(isalpha(checkcode.at(1)))...
Thus, the compiler is correct. When it sees a unary & operator, it expects the operand to be something that it can take the address of, such as an lvalue or a function.
Careful reading of error messages and code will help you find this kind of error next time. (That is, when the compiler complains about a missing "lvalue or function designator," ask yourself what would make it expect such a thing in the first place. It wants those when it's taking the address of something, so consider why it thinks it should be taking the address of anything. It does that with a unary & operator, but you intended to have a binary operator, so look closely at the code to determine why it's not interpreted as a binary operator. You know C++ syntax, so you know that if statements need to be entirely surrounded in parentheses, and so you know that only the first expression is part of the condition. That's not what you intended, so you'll realize that the closing parenthesis is in the wrong place.)
As it is, the single-ampersand & operator isn't what you should use for Boolean expressions. You should use && instead. That difference would not lead to the error you saw, and it would have no discernible effect on the run-time behavior of your code, either.

Related

Evaluate expressions until one returns true

I have a savePotentiometerState(...) -function, which returns true if the there were changes to save, and false if nothing was done. Further, I know that on any single pass through my main loop, at most one of the potentiometers may have changed (due to the way they're read out).
This is on a very time-constrained embedded platform, so it's important (or at least matters) that I don't call savePotentiometerState more often than I have to. However, the code I come up with naturally seems silly, something likely to end up at thedailywtf:
if (!savePotentiometerState(pot1))
if (!savePotentiometerState(pot2))
...
if (!savePotentiometerState(potn));
Another way to do this would be to use short-circuit evaluation:
const bool retval = savePotentiometerState(pot1) || savePotentiometerState(pot2) || ... || savePotentiometerState(potn);
I suppose I could even drop the assignment here. But this doesn't feel like good style either, since I'm abusing the short circuiting of the || operator.
The various potn objects are member variables of the containing class, so there's no obvious way to write this as a loop.
I feel like I'm missing something obvious here, so my question is: is there an idiomatic/easy to read way to do this, which doesn't sacrifice efficiency? If it matters, I'm using C++17.
Loop seems the way to go:
for (auto& pot : {std::ref(pot1), std::ref(pot2), /*..,*/ std::ref(potn)}) {
if (savePotentiometerState(pot)) {
break;
}
}
Since you can use C++17 you can leverage fold expressions and write a helper function to do the evaluation for you.
template<typename... Args>
bool returtnPotentiometerState(Args&&... args)
{
return (... || savePotentiometerState(args));
}
and then you would call it like
if (returtnPotentiometerState(pot1, pot2, ..., potn))
This means you don't have a loop, and you get short circuiting.
Personally - I'd avoid the algorithm you're using.
I'd save the state for every pot all the time; and track the current and previous values; and then only call a given callback if if the value had changed.
This way, savePotState is always as fast as it needs to be for a given pot; and you'll never get into the state where pot1 to pot(n-1) can block potn from being read.

Name for phenomenom: if if else

Last week I heared about a phenomenom about if-Statements. It had a specific name, but I can't remember it.
The Problem is about an if-if-else construction, for example:
if( a!=null )
if( a.isTrue() )
a.performAction();
else
a.healCondition(); // second chance to do something
So the problem comes from missing brackets. It wouldn't be a problem if I use brackets for the outer if.
Without brackets it is not always clear to which "if" the "else" belongs to.
But I don't want to have a solution for that problem. I would be happy to know how this pattern is called.
Thanks for your help
The ambiguity is called dangling else, and how it's solved depends on the language. Java for example has syntax rules that associate else with the inner if.
This looks like Java, but what I am saying applies to almost every "bracketed" language.
You should really try not to use multiline if statements when you don't want to use brackets.
In this case you would not want to write:
if(a!=null) if(a.isTrue()) a.performAction(); else a.healCondition();
It is ugly, so you break it up into multiple lines. As soon as you do that you should add brackets. Not for compiler (which won't need them in this case), but for other programmers and yourself:
if(a!=null)
{
if(a.isTrue()) a.performAction();
else a.healCondidiont();
}
or
if(a!=null)
{
if(a.isTrue())
{
a.performAction();
}
else
{
a.healCondidiont();
}
}

Ternary operator in bison, avoid both side computation

I have this rule in my grammer for ternary operator:
Int:
Boolean '?' Int ':' Int {if($1==1) $$=$3; else $$=$5;}
| ...
For numbers and expressions this works fine but suppose I have this code when a is integer:
a=5
1==1 ? a++ : a++
cout<<a;// now a==6 is the correct print but I got a==7
Both side of the ':' are computed but I need only one side.
How can i do it in bison?
The only way I see to accomplish what you want while keeping your one-pass interpreter approach would be to have a global flag that controls whether evaluation takes place (while that flag was set to false, the parsing rules would parse normally, but not execute anything, which you'd accomplish by enclosing each action in an if. The rule for the ternary operator could then invoke mid-rule actions or special parsing rules that set this flag according to the condition.
The proper way to solve this is by not executing the program directly in the parser. Instead let the parser build an AST (or some other intermediate representation if you prefer), which you then walk to execute the program in an additional stage.
In that stage you can then easily decide which branch to evaluate after evaluating the condition. The logic for that would look something like this:
class TernaryOperator : public IntExpression {
// ...
public:
int eval() {
if(condition.eval()) {
return then_branch.eval();
} else {
return else_branch.eval();
}
}
}
Of course the above is only an example and might be better written using the visitor pattern instead.

Infix Expressions

I am trying to evaluate an infix expression using two stacks, however, my program keeps getting a segmentation fault and I am not sure what is causing the error. I have tried following the pseudocode for the RPN algorithm, however I think my issue arises when I call doOperation. I am not sure what parameters to include when calling this. I know I need a (ValueType, char, ValueType), however I do not want to write doOperation (ch, ch, ch) since I am pretty sure that won't help. Can anyone help me figure out a way to call this function? (I'm pretty sure that's one of the reasons causing the segmentation fault).
The opStack and valStack in doOperation should use the variable in processExpression.
Its function prototype should be like this:
ValueType doOperation(ValueType operandL, char operation, ValueType operandR, stack<char>& opStack, stack<ValueType>& valueStack)
Pay attention to the last two parameters: stack<char>& opStack, stack<ValueType>& valueStack. They must be pointer-passed or reference-passed, NOT value-passed.
processExpression call doOperation like this: doOperation(operandL, ch, operandR, opStack, valueStack) .
Besides, the current segmentation fault happens because opStack and valueStack defined in doOperation has no items. top() will reference noexist value.
Try removing these lines from doOperation:
stack<char> opStack;
stack<ValueType> valStack;
operandR = valStack.top();
valStack.pop();
operandL = valStack.top();
valStack.pop();
operation = opStack.top();
opStack.pop();
Note that your declaration of double result isn't there - you should keep that.
So, what's happening in the above lines:
You create stacks opStack and valStack. Both of these are empty.
You call .top(), which does bad things when the stack is empty. .pop() does bad things on empty stacks as well.
You are attempting to assign values to the parameters you passed in. Even if this was successful, your parameters would be useless. You just end up creating/initializing them in your function any way.
Now, after removing the above lines, you'll need to change your calls to doOperation. In processExpression you will want to do these calls before calling doOperation:
operandL = valStack.top();
valStack.pop();
operandR = valStack.top();
valStack.pop();
operation = opStack.top();
opStack.pop();
doOperation(operandL, operation, operandR)
Which isn't pretty, especially when you do that for the three times you call doOperation, but it's a start. The first goal is to get working code. You can make it pretty if you're so inclined later.
Also, and this is a bit pedantic, but you should rename your operation variable to be operator, since that is what it really is. The "operation" is the thing that happens when you execute the operator.

Nested If (x) checks - Better way to write this?

There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.
For example, I have
if (a)
{
if (a->b())
{
if (a->b()->c())
{
a->b()->c()->DoSomething();
}
}
}
I really don't like the look of this. Is there a way to turn this into something more readable? Ideally,
if (a && a->b() && a->b()->c() )
{
...
}
would be great, but obviously would not work.
EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!
Why would the latter not work?
In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.
In fact, you could write:
a && a->b() && a->b()->c() && a->b()->c()->DoSomething();
Quoting from K&R1:
Expressions connected by && or || are evaluated from left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known.
Therefore the latter example will work perfectly, as WhirlWind has noted.
1 The C Programming Language, Second Edition, Page 21.
Your second example does work in C/C++. It short circuits when the first FALSE value is hit.
You've seen from the other answers that using && will work, and will short-circuit the evaluation when a null pointer is encountered.
The uneasy programmer in me likes to avoid repeating method calls for tests like this since it avoids worrying if they are idempotent or not. One option is to rewrite like this
A* a;
B* b;
C* c;
if ((a=a()) && (b=a->b()) && (c=b->c())) {
c->doSomething();
}
Admittedly verbose and a bit clunky, but at least you know each method is called just once.
Why 'obviously would not work'? Since the && operator only evaluates the right term if the left is valid, the rewrite is perfectly safe.
Since you've already received the direct answer to your question I'll just mention that long chains of calls like you've got there are a code smell and you might consider a better design. Such a design might, in this case, include use of the null object pattern so that your call might just boil down to:
a->CDoSomething();
Chaining works, but it's not necessarily the best general-case answer, particularly because it obscures the failure point. I would instead suggest flattening the tests by inverting the logic so that it exits on failure.
if (!pa)
return Fail("No pa");
B* pb = pa->b();
if (!pb)
return Fail("No pb");
C* pc = b->c();
if (!pc)
return Fail("No pc");
pc->DoSomething();
Same thing, but flat and easy to read. Also, because it immediately handles the failure case, that doesn't get relegated to an else that you might never get around to writing.
In this example, I assumed you didn't want to just silently fail, so I added Fail as a helper that logs the text and returns false. You could also just throw an exception. In fact, if the various methods signaled their failure by throwing an appropriate exception instead of returning null, then all this would be unnecessary. If silent failure was desirable, then a null object pattern would be appropriate.
if (a && a->b() && a->b()->c()) { a->b()->c()->DoSomething(); }
C++ performs lazy evaluation so this will work. First, a would be evaluated and if it's 0 the whole condition is false so there will be no evaluation of the other parts.
This works for the || operator as well. If you write if (a || b), b won't be evaluated if a is true.
Second one will work provided you want to call only DoSomething().