I am new for "C++" so I don't understand the following part of code.
The "data" is the String just like "Hello World" and seperature equals to this char "|". So what does it mean this line "data.charAt(i) == separator || i == maxIndex"
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
This:
data.charAt(i) == separator || i == maxIndex
is an expression that is contextually convertible to bool. That expression is part of the if statement condition. The || operator is a logical operator OR. Simply speaking you have:
if (A OR B)
Where A in your case is data.charAt(i) == separator and B is i == maxIndex. We can think of A and B as operands.
Due to operator precedence the compiler knows what A and B are and how to cut the entire expression into smaller expressions that make up operands. Both expressions have the equality operator == in them. So thinking about separator || i as being an expression is wrong.
The logical operator || groups left to right which means A gets evaluated first and B might not get evaluated if A is true.
Related
In the code I use an expression tree "3 + 2.53 - 1.75" that should return a result of 3.78. However, it ends up adding all the values within the string and outputs 7.28. I ran through the code multiple times on paper trying to see what happens in each iteration of the for loop where the index variables i and distance_operator are used too. As far as I have gone through it I cannot find a reason why the program continues to add each float value. By the time the '-' character is reached it should subtract the next value.
The distance_operator is used to be an offset from the first operator where index i will be pivoted so that I can take a portion of that string and calculate it using the substr() function.
float total = (float)value(expression[0]);
int distance_operator;
for (i = 1; i < expression.size(); i++) {
if (expression[i] == '+' || expression[i] == '-') {
distance_operator = i + 1;
while (expression[distance_operator] != '+' || expression[distance_operator] != '-') {
distance_operator++;
if (distance_operator == expression.size())
break;
}
if (expression[i] == '+')
total += std::stof(expression.substr(i, distance_operator - i));
else if(expression[i] == '-')
total -= std::stof(expression.substr(i, distance_operator - i));
}
}
The code is almost correct but there is an "off-by-one" error.
The problem is that when finding the - the right substring used will be "- 1.75" with a negative value when parsed as a number and you will be subtracting it, basically negating the value you wanted to use. The accumulating code should be:
if (expression[i] == '+')
total += std::stof(expression.substr(i+1, distance_operator-i-1));
else if(expression[i] == '-')
total -= std::stof(expression.substr(i+1, distance_operator-i-1));
Note that i+1 is used, so the expression sign found will be skipped.
Also note that this check
while (expression[distance_operator] != '+' || expression[distance_operator] != '-')
will always be true, because a thing is always different from A OR different from B. The correct logical operator is &&.
I have a method which looks like this:
bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
num%i == 0 ? sum += i : continue;
}
return sum == num ? true : false;
}
I'm trying to combine here ? operator with continue operator...
So logically if the statement here is false in this line:
num%i == 0 ? sum += i : continue;
I will just skip the iteration or do nothing?
If I do it like this the compiler reports an error like:
expected an expression
And in case like this:
num%i == 0 ? sum += i
It says:
Expected a ':'
Is there any way to use continue with ? operator or just simply avoid false case somehow ???
bool Perfect(int num) {
int sum = 0;
for (int i = 1; i < num; i++)
{
if(num % i == 0)
sum += i;
}
return sum == num;
}
Use an if statement. No need of continue since you have no other statement after sum += i.
C++ and C have both statements and expressions (notice that an assignment or a function call is an expression, and that expressions are statements). They are different syntactic (and semantical) things.
You could have coded (but this is weird style as a statement reduced to a ?: conditional expression) inside your for loop:
(num%i == 0) ? (sum += i) : 0;
(when num%i is non-zero, that evaluates to 0 which has no significant side effect; BTW that last occurrence of 0 could be 1234 or any constant integral expression)
Some programming languages (notably Scheme, read SICP) have only expressions (and no statements).
The ternary ?: operator applies to expressions and gives an expression (so can't be used for statements).
Conditional statements use the if keyword. In your case it is much more readable (because you are using sum += i only for its side effect) and an if statement is here easier to understand.
You can't use a ternary operator in this way. You would normally use it for assigning a value to a variable based on an expression being true or false. Eg.
int j, i,
j = (i == 2) ? 5: 10;
If i is equal to 2 then j is given the value of 5 else if i is not equal to 2 then j is given the value of 10.
As you might be able to tell im trying to introduce a counter for how many consonants there are in a certain string, but the output is always 50, unless spaces are involved.
int main(){
char input[50];
int total = 0;
cout << "Enter a string of no more than 50 characters\n";
cin.getline(input,50);
for(int n = 0; n<50;n++){
if(input[n]!='a',input[n]!='A',input[n]!='e',input[n]!='E',input[n]!='i',input[n]!='I',input[n]!='o',input[n]!='O',input[n]!='u',input[n]!='U',input[n]!=' ')
total++;}
cout << total << endl;}
According to wikipedia, comma operator is defined as follows
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type).
In your case, you should use logical AND (&&) instead of comma operation.
More efficiently, you may rewrite your code like this
char c = tolower(input[n]);
if (c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c !='u')
total++;
It will include all the cases.
As everyone has clearly explained, you need to use && operator to ensure all conditions are checked.
if(input[n]!='a' && input[n]!='A' && input[n]!='e' && input[n]!='E' && input[n]!='i' && input[n]!='I' && input[n]!='o' && input[n]!='O' && input[n]!='u' && input[n]!='U' && input[n]!=' '){
total++;
}
One recommendation to avoid multiple checks:
Extract the character to a variable converted to lower or upper case.
char c = input[n] | 32;
Regarding the ',' used; this program might provide more insight along with the WIKI shared :
void main(){
int a=-1;
if(++a,a, a++){ // Works like "||"
printf("Yes %d",a);
}else {
printf("NO %d", a);
}
}
Output: NO 1
I'm sure this has been asked a few times but the other questions I looked at didn't really help me much. Alright so here goes: I've got three functions one that converts an infix expression to a postfix, one that's a preprocessor and one that evaluates the postfix expression. What I'm having trouble with is evaluating a unary negative expression. If I put in my entire code it'll be super long so I'm only going to post up the parts that deal with the negative/minus case:
here's my output:
input: -3
after preprocess: 3
postfix = -3
then a segmentation fault when it should output " total = -3 "
#include "postfix.h"
#include "stack.h"
#include <cstdlib>
#include <cmath>
#include <cstdio>
void eval_postfix(char* postfix){
Stack<double> stack;
char fchar[100];
int j=0;
double a, b, convert, total = 0.0;
for(int i=0; postfix[i] != '\0'; i++){
switch(postfix[i]){
case '-':
a = stack.top();
stack.pop();
b = stack.top();
stack.pop();
total = b-a;
stack.push(total);
break;
I'm pretty sure the error is in that part of the function, I've been trying different things but nothing has been working, more times than not I get a segmentation fault or a zero. I originally tried to apply what I did in the infix2postfix expression (which obviously didn't work) But here's the rest of my code for the negative/minus case...
void infix2postfix(char* infix, char* postfix){
Stack<char> stack;
stack.push('\0');
int pc = 0;
bool c;
for(unsigned int i = 0; infix[i] != '\0'; i++){
//use the switch method to define what to do for each of the operators
switch(infix[i]){
case '-':
c = 0;
//unary negative
if(i==0){
postfix[pc++] = infix[i];
c = 1;
}
else if((infix[i-1] == '*' ||
infix[i-1] == '^' ||
infix[i-1] == '*' ||
infix[i-1] == '/' ||
infix[i-1] == '+' ||
infix[i-1] == '-')&&
i>0){
postfix[pc++]= infix[i];
c=1;
}
else{
if(stack.top() == '*' || stack.top() == '/' || stack.top() == '^'){
while(stack.top() != '\0' && stack.top() != '('){
postfix[pc++] = stack.top();
postfix[pc++] = ' ';
stack.pop();
}
}
}
if (c==0)
stack.push('-');
break;
void preprocessor(char* input){
char output[100];
int oc = 0;
for(unsigned int i=0; input[i] != '\0'; i++){
if((input[i] == '-' && (input[i-1] == '*' || input[i-1] == '^' || input[i-1] == '*'
|| input[i-1] == '/' || input[i-1] == '+' || input[i-1] == '-')
&& i>0)){
//output[oc++] = '0';
output[oc++] = input[i];
}
I'm almost certain that whatever error it is I made (or whatever edit I need to do) is probably something really simple that I just can't see (cause that's usually the case with me) but any nudge in the right direction would be highly appreciated!
**Note: the formatting of my code may not be accurate cause I only copied and pasted the parts I felt were relevant.
It seems to me like what is happening is that your code that evaluates the postfix expression, when it sees a minus sign, treats it as a subtraction. In particular, probably you push 3 onto the stack, and then encounter a minus sign: this triggers the code in the first block you posted, which tries to pop two elements off of the stack and subtract them. However there is only one element on the stack, namely the 3.
The result prints out 'c' 3 times, anyone know why it always meets the first condition?
#include <iostream>
using namespace std;
char x(char y)
{
if (y == 'a' || 'b')
{
return 'c';
}
else if (y == 'c' || 'd')
{
return 'e';
}
else
{
return 'g';
}
}
int main()
{
cout << x('a') << endl;
cout << x('c') << endl;
cout << x('p') << endl;
return 0;
}
You need something of the form
if (y == 'a' || y == 'b')
This is because in this expression
(y == 'a' || 'b')
you are evaluating an OR of y == 'a' and 'b', and since 'b' evaluates to true by virtue of being non-zero, the whole expression evaluates to true.
(y == 'a' || true)
This line:
if (y == 'a' || 'b')
is equivalent to:
if ((y == 'a') || ('b'))
That's because the == operator has higher precedence than the || operator.
Since 'b' is non-zero, it always evaluates as true, and so (y == 'a' || 'b') always evaluates as true.
You need to write this:
if (y == 'a' || y == 'b')
Of course, even if the precedence was the other way around,
if (y == ('a' || 'b'))
would not have been what you intended either!
Please check the operator precedence (priority) here: http://en.cppreference.com/w/cpp/language/operator_precedence
In your case the condition expression is:
(y == 'a' || 'b')
So the “y == 'a'” part is evaluated first which may be true/false depending on the value of "y". Let's call the value of "y=='a'" as "t". And then the expression is evaluated as " t || 'b'" in this case 'b' is actually the ASCII code value of character 'b' (98) which is surely larger than 0, so the result of the boolean expression is always true.
To dismiss any ambiguity caused by operator precedence, I think it's a good habit to use brackets to explicitly express your priority in the evaluation. In your case, as suggested by earlier post, it should be:
if ((y=='a') || (y=='b'))