A true if condition is being skipped [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to figure out why this condition is being skipped.. It is a 2d array, it's pretty self explanatory what's being compared. Here's the code first followed by explanation.
if ((reversed[i][j] == true) && (circle[i][j] == 'C'))
{
reversed[i][j] == false;
}
else if (circle[i][j] == 'C')
reversed[i][j] == true;
The problem is that it's skipping the else if EVEN when it's true; I've tested using a cout just before the code where I say:
cout<<circle[i][j];
and it's showing that it is indeed 'C' this is very weird, I've never seen anything like it. I hope there's something simple I'm missing.
circle is defined as follows:
char **circle;
circle = new char *[SIZE];
for (int i = 0; i < SIZE; i++)
circle[i] = new char[SIZE];

Are you sure that you wanted to write
if ((reversed[i][j] == true) && circle[i][j] == 'C'))
{
reversed[i][j] == false;
}
else if (circle[i][j] == 'C')
reversed[i][j] == true;
instead of this?
if ((reversed[i][j] == true) && circle[i][j] == 'C')
{
reversed[i][j] = false; // assignment here
}
else if (circle[i][j] == 'C')
reversed[i][j] = true; // assignment here

Related

what is wrong in this easy if else c++ code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This question is in hackerrank conditional statements and i wanted to solve it without using array.The code runs but gives wrong output. Can anyone see what is the mistake in this code , Why would it not work?
#include <bits/stdc++.h>
using namespace std;
int n ;
cin >> n ;
int main()
{
int n ;
cin>>n;
if(n=0){
cout<<"zero";
}
else if(n=1){
cout<<"one";
}
else if(n=2){
cout<<"two";
}
else if(n=3){
cout<<"three";
}
else if(n=4){
cout<<"four";
}
else if(n=5){
cout<<"five";
}
else if(n=6){
cout<<"six";
}
else if(n=7){
cout<<"seven";
}
else if(n=8){
cout<<"eight";
}
else if(n=9){
cout<<"nine";
}
else{
cout<<"Greater than 9";
}
return 0;
}
You should use '==' not '='
because "if (n=1)" behaves the same as "if(true)"
== is compare
= is assignement

Why I am getting this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000478 at pc 0x0000003a5517 bp 0x7ffe2f5c2670 sp 0x7ffe2f5c2668
Here is my code:
class Solution {
public:
vector summaryRanges(vector& nums) {
if(nums.size() == 0)
return {};
if(nums.size() == 1)
return {to_string(nums[0])};
vector<string> ans{};
int i=0,j=1,initial=nums[0];
if(nums.empty()||nums.size()==0)
return ans;
while(j<=nums.size())
{
if(i<nums.size())
{
if(nums[i]+1==nums[j])
{
i++;
j++;
}
else
{
string str3;
if(initial!=nums[i])
{
string str = to_string(initial);
string str1= to_string(nums[i]);
string str2 = "->";
str3=str+str2+str1;
}
else
{
str3 = to_string(initial);
}
ans.push_back(str3);
initial=nums[j];
i=j;
j++;
}
}
else
{
string str = to_string(initial);
ans.push_back(str);
}
}
return ans;
}
};
I think you are accessing an index out of vector size . Index j is probably going out of bounds .
while(j< = nums.size())
and
nums[j]
This
while(j<=nums.size())
and these
if(nums[i]+1==nums[j])
...
initial=nums[j];
look very suspicious. If j == nums.size() then nums[j] is an out of bounds error on num. Maybe you meant this?
while(j<nums.size())
(I.e. the same as you have with the i variable).

Strangeness with dynamic arrays in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am honestly not quite sure what is going on here.
It has been years since I have programmed in C++, but I am trying to execute this code
short* result = new short[3];
now, I would expect that this creates an array with 3 memory locations: 0,1 and 2, but for what ever reason, this works:
result[0] = someObject::parseShort();
but this does not work:
result[1] = someObject::parseShort();
no exception is thrown, but it is like addresses 1 and 2 dont even exist? I have verified this with visual studio's debugger, and this is leading to some very interesting results when I try to read from those memory addresses, no matter what I Initially wrote to them, they always seem to return 0
Like I said, its been years since I've written anything in C++, and would appreciate someone being able to tel me what is going on? because as far as I can tell, it looks like I am defining the array right?
EDIT:
here is the rest of the relevent code:
phoneNumber::phoneNumber(string number)
{
short* nbrs = parseNumber(number);
areaCode = nbrs[0];
prefix = nbrs[1];
this->number = nbrs[2];
delete[] nbrs;
}
areaCode, prefix, and number are all members of the class.
area code gets set correctly, but prefix and number dont seem to
here is the definition of parseNumber:
short* phoneNumber::parseNumber(string num)
{
if (num == "")
throw new exception("value should not be null");
int var= 3;
short* result= new short[var];
string temp = "";
bool fail = false;
int j = 0;
bool ready = false;
num = Utils::removeSpaces(num);
if (j ==0&&num[0] != '(')
{
fail = true;
}
for (int i = 1; i < num.length(); i++)
{
if (fail)
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
if (num[i] >= '0' && num[i] <= '9')
{
temp+=num[i];
continue;
}
else if (j== 0 && num[i] ==')')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if(j==1 && num[i] =='-')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if (j == 3 && i == num.length() -1)
{
if(temp.length() != 4)
{
fail = true;
continue;
}
ready = true;
}
else
{
fail = true;
continue;
}
if (ready)
{
result[j]= Utils::parseShort(temp);
j++;
temp = "";
ready = false;
continue;
}else
{
temp+= num[i];
}
}
if (temp.length()==4)
result[j]= Utils::parseShort(temp);
else
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
return result;
}
Yes, you are defining your array right. You have a bug elsewhere in your code outside the part that constitutes your question.

Receiving stack errors when trying to evaluate a postfix expression in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am getting 3 errors when I try to use stacks when I want to evaluate a postfix expression. I am not very experienced with the usage of stacks so please be patient with me.
Here is my code:
int Expression::evaluate(string postfix)
{
// ERROR 1 //
stack<int> resultStack = new stack<int>();
int length = postfix.length();
for (int i = 0; i < length; i++)
{
if ((postfix[i] == '+') || (postfix[i] == '-') || (postfix[i] == '*') || (postfix[i] == '/') || (postfix[i] == '^') || (postfix[i] == 'sqrt') || (postfix[i] == 'log') || (postfix[i] == 'abs') || (postfix[i] == '~'))
{
// ERROR 2 //
int result = doTheOperation(resultStack.pop(), resultStack.pop(), postfix[i]);
resultStack.push(result);
}
else if ((postfix[i] >= '0') || (postfix[i] <= '9'))
{
resultStack.push((int)(postfix[i] - '0'));
}
else
{
}
}
// ERROR 3 //
return resultStack;
}
//The operations that must be done if a specific operator is found in the string
int Expression::doTheOperation(int left, int right, char op)
{
switch (op)
{
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '^':
return pow(left,right);
case 'sqrt':
if(right < 0)
{
string temp = "Square root of a negative number.";
throw temp;
}
else
{
return (sqrt(right)) ;
}
case 'log':
if (right < 0)
{
string temp = "Error. Not able to get the log of zero.";
throw temp;
}
else
{
int temp = log10(right);
return ceil(temp);
}
case 'abs':
if (right < 0)
{
return (right*-1);
}
else
{
return right;
}
case '~':
return (right*-1);
default:
return -1;
}
return -1;
}
Then it gives me the following errors:
error 1: conversion from 'std::stack<int>*' to non-scalar type 'std::stack<int>' requested
error 2: invalid use of void expression
error 3: cannot convert 'std::stack<int>' to 'int' in return
I will mark in the code where exactly these errors are occuring. I have absolutely no idea why I am getting these errors.
Error 1:
The operator new returns a pointer to a dynamically allocated object (here std::stack<int> *) in the free store, but you just want to create a stack as a local variable (std::stack<int>).
Change the line to:
stack<int> resultStack;
Error 2:
You call resultstack.pop(), certainly expecting that it returns an int and pops it from the stack. unfortunately, pop() is void. It returns nothing, so you can't pass this result as a parameter.
Even if it would return an int, you would have a hidden error: you have no garantee about the order of evaluation of parameters in a function call. So you do not know for sure wich of the two pops is done first.
Change the line to:
int p1 = resultStack.top(); resultStack.pop();
int p2 = resultStack.top(); resultStack.pop();
int result = doTheOperation(p1, p2, postfix[i]);
Error 3:
Your function is defined as returning an int. But you try to return the whole resultStack, which is a stack.
If you want to return just the last value remainint on top of the stack, change the line to:
return resultStack.top()

C++ if-else if Issues [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having issues with my program below. It should convert numbers between 1-100 to AA,BA,BB,CB,CC,D,F. But it stops working and shows "BA" if I enter number less than 84. I checked the code. But I don't understand what is the problem.
#include <iostream>
using namespace std;
int main() {
int secenek,notu;
cout << "Not Dönüştürücü" << endl;
cout<<"Başlamak için 1'e basın:\n";
cin>>secenek;
if (secenek==1)
{
cout<<"Dönüştürülecek not: ";
cin>>notu;
}
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<75 || notu>69)
{
cout<<"CC";
}
else if (notu<70 || notu>59)
{
cout<<"D";
}
else if (notu<60)
{
cout<<"F";
}
}
you made a logical error:
else if (notu<90 || notu>84)
should be
else if (notu<90 && notu>84)
and the same goes for all the following conditions.
EDIT as #Jarod42 suggested; you don't even need to check notu<90 anymore... your code could look like this:
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu>84)
{
cout<<"BA";
}
else if (notu>79)
{
cout<<"BB";
}
etc...
Your condition
else if (notu<90 || notu>84)
will always be true, whatever notu is set to. You probably mean
else if (notu < 90 && notu > 84)
The problematic part:
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<90 || notu> 84) will trigger on any notu lower than 90 and on any notu higher than 84. That's all pretty much all who survived the earlier check.
Correct implementation would be else if (notu<90 && notu> 84) which will only trigger if both conditions are met.
My C++ is a bit rusty, but if I remember correctly one could even write else if (84 < notu < 90).
EDIT: else if (84 < notu < 90) isn't valid C++ syntax.
The main problem is that you're using || where && would be logically correct.
But you don't really need && either - you can simplify a bit since in the else branch you already know that the corresponding if condition is false.
Like this:
if (notu < 0 || notu > 100)
{
cout << "Geçerli bir not girin.\n";
}
else if (notu >= 90)
{
cout << "AA";
}
else if (notu >= 85) // Already know that it's < 90, because it's not >= 90
{
cout << "BA";
}
// ...
// ...
else if (notu >= 60) // Already know that it's < 70
{
cout << "D";
}
else // Already know that it's < 60
{
cout << "F";
}