Error passing strings and char to bool function - c++

I am trying to create a function that looks at a '-' sign and checks whether is a minus sign or a negative sign based on if it has a ' ' (space) in front of it. I am doing so by comparing the current char I have (infix[x]) and comparing to infix[x+1]; I keep getting error but im unsure if its because im not passing correctly or something else?
for(unsigned x = 0; x < infix.length(); ++x)
{
// place numbers (standard, decimal, & negative)
// numbers onto the 'postfix' string
if((isdigit(infix[x])) || (infix[x] == '.'))
{
postfix += infix[x];
}
else if ((infix[x] == '-'))
{
if(checkfornegative(infix[x], infix)== 1)) // error: expected primary-expression before ‘)’ token
if(checkfornegative(infix[x], infix)== 1))
{
postfix+= " ";
}
else if(checkfornegative(infix[x], infix)== 0)) //error: expected primary-expression before ‘)’ token
if(checkfornegative(infix[x], infix)== 1))
{
postfix += infix[x];
}
}
// This is the function in using
bool checkfornegative(char C, string& QQ)
{
bool status;
if((C == '-') && (QQ[C+1] == ' '))
{
status = true;
}
else if((C == '-') && (QQ[C+1] != ' '))
{
status = false;
}
return status;
}

You are getting compilation errors because you have extra closing parenthesis in the if conditions.
if(checkfornegative(infix[x], infix)== 1)) // error: expected primary-expression before ‘)’ token
Remove the last closing parenthesis from the condition. Same goes for the second condition also.
However, there are several issues in your code but they are not compilation errors.

Related

Checking balanced parantheses code is not behaving as per expectation

I am solving a question in which I have to check if the input string of parentheses are balanced or not,
and if not, code is expected to return the 1-based index of unmatched closing parenthesis, and if not found, return the 1-based index of the opening parenthesis. My code runs fine if I implement only the parenthesis checking part, but as I try to implement the returning index part, the code starts giving 'success' output for all the input.
Here is the code:
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
int process_input( string value );
bool closing_bracket_match(char opening_bracket, char closing_bracket);
bool closing_bracket_match(char opening_bracket , char closing_bracket){
if( (opening_bracket == '{' && closing_bracket == '}') || (opening_bracket == '(' && closing_bracket == ')') || (opening_bracket == '[' &&
closing_bracket == ']') ){
return true;
}
else{
return false;
}
}
int process_input( string value ){
stack<char> processed_input{};
int unmatched_index{};
for( size_t i{}; i< value.size() ; ++i ){
if( value.at(i) == '{' || value.at(i) == '(' || value.at(i) == '[' ){ // check for opening brackets
processed_input.push(value.at(i)); // Appending opening bracket into the stack
}
else if( (value.at(i) == '}' || value.at(i) == ')' || value.at(i) == ']') && (processed_input.empty() == false) &&
closing_bracket_match(processed_input.top(),value.at(i)) ){ // the bracket in stack would be popped
processed_input.pop(); // matching brackets ar removed
}
}
if( processed_input.empty()==true ){
return 0;
}//This part is causing the bug
if(processed_input.empty() == false){
auto it = find( value.begin(), value.end(), processed_input.top() );
if( it!= value.end() ){
unmatched_index = distance(value.begin() , it)+1; //returning the 1 -based index of unmatched bracket
}
return unmatched_index;
}
}
int main(){
string input{};
cout<<"Please enter the code here: "; // debug line
cin>> input;
int result{};
result = process_input(input);
if( result == 0 ){
cout<<"Success";
}
else{
cout<<result;
}
}
If you want to return a position of the last (innermost) unmatched paren, you need to store it together with its position on the stack. Seeking for it leads to errors.
Which of potentially several items equal to the one you seek will find() find?
For example, in "(((" there are three unmatched opening parentheses, and all of them are equal to '('. Which one do you want to return as a result? Which one do you actually return?
And how about this input: "()("...?
Added
Here is a possible solution. Please note how it does not find() anything, but it stores on a stack all information necessary to produce the desired output.
#include<iostream>
#include<string>
#include<stack>
using std::string;
using std::stack;
bool is_opening(char c) {
return c == '(' || c == '[' || c == '{';
}
bool is_closing(char c) {
return c == ')' || c == ']' || c == '}';
}
bool is_matching(char opn, char cls) {
switch(opn) {
case '(': return cls == ')';
case '[': return cls == ']';
case '{': return cls == '}';
}
return false;
}
int process_input( string value )
{
stack<char> opn_parens{};
stack<size_t> positions{};
for( size_t i{}; i < value.size() ; ++i )
{
const char ch = value.at(i);
if( is_opening(ch) )
{
opn_parens.push(ch);
positions.push(i);
}
else if( is_closing(ch) )
{
if( opn_parens.empty() ) // a closing paren with no unmatched opening one
return i + 1;
const char opn_ch = opn_parens.top();
const size_t opn_pos = positions.top();
if( ! is_matching(opn_ch, ch) ) // unmatched closing paren
return opn_pos + 1;
opn_parens.pop(); // remove a matched paren
positions.pop();
}
}
if( ! positions.empty() ) // some unmatched parens remain
return positions.top() + 1;
return 0;
}
int main(){
std::cout << process_input("hello(mum[]{(dad()[bro!])})") << std::endl;
std::cout << process_input("))") << std::endl;
std::cout << process_input("([") << std::endl;
std::cout << process_input("([)") << std::endl;
std::cout << process_input("([{") << std::endl;
}
You can see it working at https://godbolt.org/z/e8fYW5fKz

Wrote a C++ code to check if expression has balanced parenthesis and my code is not running. I have been stuck for a day now

The code is given below. There is no syntax error and the code used to run perfectly fine if i checked match for only () parenthesis but after i added some if.. else.. statements to check match for other brackets, my code broke. I am unable to figure out my mistake. Please Help!! I think i did some silly mistake but can't figure out what.
// structure of a stack
struct stackStructure
{
// top pointer of the stack
int top;
// pointer to the array/stack
char *array;
}stack;
// function to push element to stack
void push(char data)
{
if(stack.top == 999)
{
cout<<"Stack Overflow"<<endl;
return;
}
else
{
// incrementing the top and then pushing data to the stack
stack.top++;
stack.array[stack.top]= data;
}
} // end of push() function
// function to pop elements from the stack
char pop()
{
if(stack.top == -1)
return '\0';
else
// returning the popped value and then decrementing the top pointer
return stack.array[stack.top--];
} // end of pop() function
int main()
{
// match variable to keep track that closing bracket and opening brackets are in sequence
char match= '\0';
bool isMatching= true;
// resetting the stack variables and attributes
stack.top= -1;
stack.array= new char[1000];
cout<<"Enter the Expression to match the parenthesis: ";
cin>>stack.array;
// traversing through the character array and matching parenthesis
for(int i=0; stack.array[i] != NULL; i++)
{
// if character is an opening bracket
if(stack.array[i] == '(' || stack.array[i] == '{' || stack.array[i] == '[')
push(stack.array[i]);
// if character is a closing bracket
else if(stack.array[i] == ')' || stack.array[i] == '}' || stack.array[i] == ']')
{
match= pop();
if(stack.array[i] != match)
isMatching= false;
}
// if character is anything else we do nothing
else
continue;
}
if(isMatching == true)
cout<<"Parenthesis Matched"<<endl;
else
cout<<"Not matched"<<endl;
return 0;
}
You have 2 bugs. The first is reading your input string into your stack, this will at minimum get very confusing and at worst not work.
The second is that when checking for matching tags you check that the opening bracket is the same as the closing one, this will never be true, you need to check that the opening bracket is the same type as the closing one.
One way of solving both bugs would be:
int main()
{
// match variable to keep track that closing bracket and opening brackets are in sequence
char match = '\0';
bool isMatching = true;
// resetting the stack variables and attributes
stack.top = -1;
stack.array = new char[1000];
std::string input;
cout << "Enter the Expression to match the parenthesis: ";
cin >> input;
std::map<char, char> opening = { { ')', '(' }, { '}', '{' }, { ']', '[' } };
// traversing through the character array and matching parenthesis
for (char ch : input)
{
// if character is an opening bracket
if (ch == '(' || ch == '{' || ch == '[')
push(ch);
// if character is a closing bracket
else if (ch == ')' || ch == '}' || ch == ']')
{
match = pop();
auto open = opening.find(ch);
if (open == opening.end() || open->second != match )
isMatching = false;
}
}
if (isMatching == true)
cout << "Parenthesis Matched" << endl;
else
cout << "Not matched" << endl;
delete[] stack.array;
return 0;
}

Online C++ Grader Syntax Issue

Im trying to use an online marker for a c++ programming site. The code runs fine on my computer. However, the site is repeatedly having a compilation error, spitting out these syntax errors:
/data/grader/2/81322/compile/source.cc: In function �int main()�:
/data/grader/2/81322/compile/source.cc:16: error: expected initializer before �:� token
/data/grader/2/81322/compile/source.cc:45: error: expected primary-expression at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected �;� at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected primary-expression at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected �)� at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected statement at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected �}� at end of input
/data/grader/2/81322/compile/source.cc:45: error: expected �}� at end of input
#include <iostream>
#include <string>
using namespace std;
int main()
{
char vowels[] = { 'a', 'e', 'i', 'o', 'u' };
string word;
string newWord;
getline(cin, word);
for (int i = 0; i < (int)word.length(); i++) {
bool vowel = false;
char closest = 'z';
int close = 200;
for (char &n : vowels) {
if (n == word[i]) {
vowel = true;
break;
}
else if (abs(n-word[i]) < close) {
closest = n;
close = abs(n - word[i]);
}
}
newWord += word[i];
if (!vowel) {
newWord += closest;
if (word[i] == 'z') {
newWord += 'z';
break;
}
char next = word[i]+1;
for (char n : vowels) {
if (n == next) {
vowel = true;
break;
}
}
newWord += ((vowel) ? word[i] + 2:next);
}
}
cout << newWord << endl;
//system("pause");//remove
}
Being new to C++, I cant seem to make sense of this.
Thanks in advance.

C++ parenthesis matching application

I have to write a function that accepts a string and returns a bool. The string passed in is a series or different parenthesis opened or closed ex.({[]}) and returns whether the 'parens' are well-balanced. This has to be implemented by adding items to a stack. I am getting the following error:
parenMatching_demo.cpp:18:12: error: no match for 'operator==' in 'c
== '('
The psudocode is:
matcher(expression)
for each character in expression
if the character is an opener
push on stack
else if the character is a closr
if stack is empty return false
if the (opener at) the top of the stack does not match the closer
return false
pop the stack
if the stack is not empty return false
return true
This is what I have.
template <typename T>
bool parenMatching(string c) {
stack<string> s;
for (int i = 0; i < s.size(); i++) {
if (c == '(' || c == '[' || c == '{' || c == '<')
s.push(c);
else if (c == ')' || c == ']' || c == '}' || c == '>') {
if (s.empty()) return false;
if (s.top() != '(' || s.top() != '[' || s.top() != '{' || s.top() != '<')
return false;
s.pop();
}
}
}
One problem is the type of the stack, it should be
stack<char> s;
Then the for loop, the condition should be
i < c.size()
The next problem is
if (c == '(' || c == '[' || c == '{' || c == '<')
does not compare the character of the string c at i, so you need
const char c2 = c[i];
if (c2 == '(' || c2 == '[' || c2 == '{' || c2 == '<')
If you need help to fix the rest, let me/us know :)
You're comparing a string with a char in your codes that check for the parentheses. You're missing a line where you get the current character you're looking at as you iterate your string - you probably want something like:
char current = c.at(i);
Additionally, you need to fix your stack type as Daniel Frey says in his answer.
edit - he's since changed his to contain this info, so that answer should have everything you need.

C++ infix to postfix

I get the following error when I compile:
convert.cpp: In function 'std::string convert()':
convert.cpp:62: error: expected primary-expression before 'else'
convert.cpp:62: error: expected `;' before 'else'
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
Code:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
string infix; // infix expression string
string operand;
string operate;
stack <string> mystack; // this stack is used to push the operator
string postfix; // postfix string where the operand is appended
//....................................................................
// this function read the infix expression from user
string input()
{
cout<<" Enter the damn infix expression: "<<endl;
getline(cin, infix);
return infix;
}
//......................................................................
// this function checks for operator precedence in the stack
int precedence(string e)
{
int f;
if(e == "*" || e== "/" || e =="%")
f = 2;
else
{
if(e == "+" || e == "-")
f = 1;
}
if(e=="."){
f=0;
}
return f;
}
//....................................................................
// This function converts infix to postfix
string convert()
{
for(int i=0; i<infix.length(); i++)
{
switch(infix[i]){
// operate case start
case '+': case'-': case'*': case'/': case'^': case '(': case ')': case'.':
operate=infix[i];
{
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else
{
while(precedence(operate)<= precedence(mystack.top()))
{
postfix.append(mystack.top());
mystack.pop();
}
mystack.push(operate);
}
}
}//operate case closed
default: //when operand string char is parsed
{
operand=infix[i];
postfix.append(operand);
break;
} // default case closed
}//switch closed
}
while(!mystack.empty())
{
postfix.append(mystack.top())
mystack.pop();
}
return postfix;
cout<<postfix;
}
//...................................................................
int main()
{
input();
convert();
cout<<"postfix is "<<postfix<<endl;
}
It appears that your code is just missing some closing braces. That's all.
For example, look at this:
operate=infix[i];
{
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else
{
while(precedence(operate)<= precedence(mystack.top()))
Where is the closing } before the else statement. Just go through your code and fix these silly mistakes.
It would be a lot easier to rid yourself of these things if you made your spacing and indentation a little neater.
The "expected primary expression before else" diagnostic is the compiler-author's way of reporting you rudely foisted on him an "else" without either a preceding "if" or (what amounts to the same thing) "else if". Alexander Rafferty correctly points out that this is because the code has ...
if (condition) {
// ...
else { }
... when perhaps what you meant was ...
if (condition) {
// ...
}
else {
}
... though maybe you deleted a whole bunch of stuff by accident, and were lucky enough that the deletion resulted in unparseable code, so you will realize that something is wrong.
Look at these lines:
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else