Here is my code. It keeps saying I am doing the conversion wrong. What am I doing wrong, and can anyone help me fix this?
#include <iostream>
#include <fstream>
#include "StackAr.h"
using namespace std;
struct token{
int curLine = 1, lastLine = 1;
char next;
};
int main(int argc, char *argv[])
{
ifstream inf(argv[1]);
token t1;
typedef token *t_ptr; //assign a pointer to a struct
t_ptr ptr = &t1;
t_ptr end;
StackAr<t_ptr> stack;
while (inf >> t1.next)
{
if (t1.next == '{' || t1.next == '(' || t1.next == '[')
{
t1.lastLine = t1.curLine;
ptr -> next;
stack.push(ptr);
new token;
}
else if (t1.next == '}' || t1.next == ')' || t1.next == ']')
{
t1.lastLine = t1.curLine;
char previous = stack.topAndPop(); // get previous bracket
// deal with null
switch(t1.next)
{
case '}' : if (previous != '{') {printError(&t1.next, t1.curLine); return 1;} break;
case ')' : if (previous != '(') {printError(&t1.next, t1.curLine); return 1;} break;
case ']' : if (previous != '[') {printError(&t1.next, t1.curLine); return 1;} break;
}
}
if (inf.peek() == '\n')
t1.curLine++;
}
inf.close();
if (!stack.isEmpty())
{
char previous = stack.topAndPop()-> next;
printError(&previous, t1.lastLine);
return 1;
}
cout << "OK" << endl;
return 0;
}
In function int main(int, char**):
mockbalance.cpp:64:38: error: invalid conversion from ‘`token*`’ to ‘`char`’ [-fpermissive]
char previous = stack.topAndPop(); // get previous bracket
mockbalance.cpp:82:36: error: invalid conversion from ‘`token*`’ to ‘`char`’ [-fpermissive]
char previous = stack.topAndPop()-> next;
edit: the above code has been given a temporary fix as suggested by one of the users in the comment section but i fully recommend using a better structure also look at comments. Given notice any one who plans to use this, ago ahead but keep in mind this code in particular has been already submitted to moss database and should be used to learn.
Related
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
I'm solving a LeetCode problem and I'm getting the following error:
> Line 15: Char 23: fatal error: invalid operands to binary expression ('char' and 'void')
else if(c != st.pop())
1 error generated.
I set the stack to char type, but it seems to treat it as a void type? What could be going wrong?
My code:
class Solution {
public:
bool isValid(string s)
{
if(s.length() == 0)
return true;
stack<char> st;
for(char &c : s) {
if(c == '(')
st.push(')');
else if(c == '[')
st.push(']');
else if(c == '{')
st.push('}');
else if(st.empty() || c != st.pop())
return false;
}
return st.empty();
}
};
std::stack::pop() doesn't have a return value.
When you do c != st.pop(), compiler sees "compare char value with void value", what makes no sense.
Possible solution would be to first get the value from top to temp variable, then pop() and at least compare them:
else {
if (st.empty())
return false;
char temp = st.top();
st.pop();
if(c != temp)
return false;
}
This is code to find out the position of the unbalanced bracket in the given input. If there is no unbalanced bracket then the output is Success. When I output the top of the stack I get garbage values in C++. How to avoid it? Why does it happen?
Here Bracket is the struct that contains the position of the element and the type of element.
int main() {
std::string text;
getline(std::cin, text);
stack <Bracket> opening_brackets_stack;
for (int position = 0; position < text.length(); ++position) {
char next = text[position];
if (next == '(' || next == '[' || next == '{') {
Bracket *l1 = new Bracket(next, position + 1);
opening_brackets_stack.push(*l1);
cout<<opening_brackets_stack.top().type<<" "
<<opening_brackets_stack.top().position<<endl;
}
}
}
Here is the declaration of Bracket
struct Bracket
{
char type;
int position;
Bracket(char type, int position)
{
type =type;
position=position;
}
bool Matchc(char c) {
if (type == '[' && c == ']')
return true;
if (type == '{' && c == '}')
return true;
if (type == '(' && c == ')')
return true;
return false;
}
};
There's a couple of problems with your code, but to get into specifically what your issues is.
It is assigning local variables to themselves instead of to the data members.
Change
Bracket(char type, int position)
{
type =type;
position=position;
}
to
Bracket(char type, int position)
{
this->type =type;
this->position=position;
}
or use initializer lists and differing names
Bracket(char in_type, int in_position)
: type(in_type)
, position(in_position)
{
}
You also have memory leak here
Bracket *l1 = new Bracket(next, position + 1);
opening_brackets_stack.push(*l1);
this is better written with automatic storage duration as
Bracket l1{next, position + 1};
opening_brackets_stack.push(l1);
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.
I am having some trouble with a program that is supposed to take a command line expression and interpret it as a normal mathematical expression.This is what I am getting as an error:
driver.cpp: In function ‘int main(int, char**)’:
driver.cpp:17:57: error: no matching function for call to‘PrefixCalculator::eval(std::istringstream)’
driver.cpp:17:57: note: candidate is:
PrefixCalculator.h:33:3: note: T PrefixCalculator::eval(std::istringstream&) [with T = int, std::istringstream = std::basic_istringstream]
PrefixCalculator.h:33:3: note: no known conversion for argument 1 from ‘std::istringstream {aka std::basic_istringstream}’ to ‘std::istringstream& {aka std::basic_istringstream&}’
I can't understand what the error is trying to suggest to me.
Any suggestions for fixing that? I'm going to add exceptions later, so they are commented out for now.
This is the code:
PrefixCalculator.cpp
#pragma once
#include <sstream>
using namespace std;
template<class T>
class PrefixCalculator {
public:
PrefixCalculator(void){
numOperator = 0;
numOperand = 0;
};
~PrefixCalculator(void){};
T eval(istringstream&);
int getNumOperator() {
return numOperator;
};
int getNumOperand() {
return numOperand;
};
private:
//if you feel you need private helper functions and/or helper data
int numOperator;
int numOperand;
};
template<class T>
T PrefixCalculator<T>::eval(istringstream& input) {
//this function needs to throw an exception if there's a problem with the expression or operators
char nextChar = input.peek();
//this while loop skips over the spaces in the expression, if there are any
while(nextChar == ' ') {
input.get(); //move past this space
nextChar = input.peek(); //check the next character
}
if(nextChar == '+') {
input.get(); //moves past the +
numOperator++;
return eval(input) + eval(input); //recursively calculates the first expression, and adds it to the second expression, returning the result
}
/***** more operators here ******/
if(nextChar == '-') {
input.get();
numOperator++;
return eval(input) - eval(input);
}
if(nextChar == '*') {
input.get();
numOperator++;
return eval(input) * eval(input);
}
if(nextChar == '/') {
input.get();
numOperator++;
return eval(input) / eval(input);
}
/****** BASE CASE HERE *******/
//it's not an operator, and it's not a space, so you must be reading an actual value (like '3' in "+ 3 6". Use the >> operator of istringstream to pull in a T value!
input>>nextChar;
T digit = nextChar - '0';
numOperand++;
return digit;
//OR...there's bad input, in which case the reading would fail and you should throw an exception
}
driver.cpp
#include <sstream>
#include <string>
#include <iostream>
#include "PrefixCalculator.h"
using namespace std;
int main(int argc, char** argv) {
PrefixCalculator<int> calc;
string expression;
cout << "Give a prefix expression to evaluate, or q to quit." << endl;
getline(cin,expression);
while(expression[0] != 'q') {
//try {
int result = calc.eval(istringstream(expression));
cout << result << endl;
//}
//catch { //will not compile, you have to finish this!
//
//}
cout << "Give a prefix expression to evaluate or q to quit." << endl;
getline(cin,expression);
}
return 0;
}
calc.eval(istringstream(expression)); passes a temporary instance to eval(), you'll need an lvalue.
Provide an extra variable for the stream
istringstream iss(expression);
and pass that one
int result = calc.eval(iss);