Full code is below. Any feedback is welcomed.
I am trying to implement syntax error reporting like GCC and other interpreters/compilers. I am sure this can be improved and hence why I was pointed to this part of Stackexchange from SO.
Full program:
#include <iostream>
#include <string.h>
#include <string_view>
#include <iomanip>
#include <cstring>
#include <stack>
int main(int argc, char const *argv[])
{
std::string code = "(* n (fac (- n 1))";
int line = 0;
int column = 0;
int position = 0;
int length = code.length();
bool balanced;
std::stack<char> parantheses_stack;
for(const char c: code){
if(c == '\n'){
++line;
column = 0;
} else {
++column;
}
if(c == ')' && parantheses_stack.empty())
balanced = false;
else if(c == '('){
parantheses_stack.push(c);
continue;
}
else if(!parantheses_stack.empty() && c == ')'){
if(parantheses_stack.top() == '('){
parantheses_stack.pop();
}
else if(parantheses_stack.top() != '('){
balanced = false;
}
}
}
balanced = (!parantheses_stack.empty()) ? false : true;
if(!balanced){
printf("Data:\nline: %d\ncolumn: %d\nposition: %d\nlength: %d\n\n", line, column, position, length);
printf("Syntax error:%d, %d parathesis out of balance, expected a ')'\n", line, column + 1);
std::cout << code + "\n";
std::cout << std::setw(column + 2) << "^\n";
}
system("pause");
return 0;
}
Output:
