Big papi 0 Newbie Poster
 QUESTION:You are required to write a program that performs syntax checking for a given computer program
  Hey Everyone i need your help badly can anyone please modify my code below

against the following rules:
• The code always starts with begin keyword and ends with the end keyword
• The conditional statements start with if keyword and ends with endif keyword
• There may be zero, one or more elseif within if—endif block
• There may be zero or one else within if—endif block
• There are two kinds of loops: The for loop block ends with endfor, and while loop block
ends with endwhile.
• The brackets must be balanced. The inner brackets must close before the outer brackets.
Following is example of balanced brackets:
/{ { ( ) } ( ) }/
• Following is an example of imbalanced brackets (note the sequence of last two closing brackets):
/{ { ( ) } ( } )/
Your program must check that the given code is free of the following errors:
• begin without end
• end without begin
• if without endif
• elseif without if
• else without if
• endif without if
• for without endfor
• endfor without end
• while without endwhile
• endwhile without while
• Imbalanced {} and () brackets
In case of an error (mismatched keyword or bracket) your program should print an error message,
properly showing the keyword which was mismatched, and the line of code where the mismatch is seen//

#include<iostream>
#include<cstring>
#include<stack>
#include<fstream>

using namespace std;

stack <string> s;

void stk(string m) 
{
    if ( m == "begin" || m == "if" || m == "for" || m == "while" || m == "{" || m == "(" ) 
    {
        s.push(m);
    }

    else if ( m == "elseif" && s.top() == "if" )
    {
        s.push(m);
    }

    else if ( m == "else" && s.top() == "if" )
    {
        s.push(m);
    }

    else if ( m == "endif" ) 
    {
        if ( s.top() != "if" )
        {
            cout << "[WARNING] 'endif' is not allowed withoud 'if'" << endl;
            return;
        }

        else if ( s.top() == "if" )
        {
            s.pop();
        }
    }

    else if ( m == "endfor" )
    {
        if ( s.top() != "for" )
        {
            cout << "[WARNING] 'endfor' is not allowed withoud 'for'" << endl;
            return;
        }

        else if ( s.top() == "for" )
        {
            s.pop();
        }
    }

    else if ( m == "endwhile" )
    {
        if ( s.top() != "while" )
        {
            cout << "[WARNING] 'endwhile' is not allowed without 'while'" << endl;
            return;
        }

        else if ( s.top() == "while" )
        {
            s.pop();
        }
    }

    else if ( m == "}" )
    {
        if ( s.top() != "{" )
        {
            cout << "[WARNING] '}' is not allowed withoud '{'" << endl;
            return;
        }

        else if ( s.top() == "{" )
        {
            s.pop();
        }
    }

    else if ( m == ")" )
    {
        if ( s.top() != "(" )
        {
            cout << "[WARNING] ')' is not allowed withoud '('" << endl;
            return;
        }

        else if ( s.top() == "(" )
        {
            s.pop();    
        }
    }

    else if ( m == "end" )
    {
        if ( s.top() != "begin" )
        {
            cout << "[WARNING] 'end' is not allowed withoud 'begin'";
            system("pause");
            return;
        }

        else if ( s.top() == "begin" )
        {
            s.pop();
        }
    }
}

void syntaxChecker() 
{
    if ( s.empty() == true || s.top() == "elseif" || s.top() == "else") 
    {
        cout << "No syntax error found";
    }

    else if (s.top() == "{" )
    {
        cout << "Expected '}' ";
    }

    else if (s.top() == "(" )
    {
        cout << "Expected ')' ";
    }

    else if (s.top() == "if" )
    {
        cout << "Expected 'endif' ";
    }

    else if (s.top() == "while" )
    {
        cout << "Expected 'endwhile' ";
    }

    else if (s.top() == "for" )
    {
        cout << "Expected 'endfor ";
    }
}

int main ()
{
    //string code;
    //readfile();
    string ch;

    fstream new_file; 
    new_file.open("ENTER FILE ADDRESS HERE",ios::in);  

    if(!new_file) 
    cout<<"No such file"; 
    else 
    { 
    cout<<"File opened successfully!\n\n";

    while (!new_file.eof()) 
    { 
    new_file >>ch; 
    cout << ch;   
    }

    new_file.close();    
    }

    do
    {
        stk(ch);
    }
    while(ch != "end");

    syntaxChecker();
    return 0;
}

I just need to enter a file(TXT) using file handling and then the program will chk whther the code given in file is balanced or not according to above certain conditions. Can anyone kindly enough can do this for me. That will be very helpful

Dani AI

Generated

Notes for — concise plan and fixes to make the checker reliable and easy to debug.

Read the file line-by-line (keep a line counter) and tokenize into reserved keywords (begin/end, if/elseif/else/endif, for/endfor, while/endwhile) plus single-character bracket tokens {, }, (, ). Use a stack of entries that include the token and the line where it was seen. Push opening tokens (begin, if, for, while, {, () with their line number. On a closer (end, endif, endfor, endwhile, } or )), first check stack.empty(); if empty report the stray closer and its line. Otherwise compare the closer to the top token and either pop the matching opener or report a mismatch showing the closer, its line, and the opener with its line. At EOF report any remaining openers as missing closers.

Handle if/elseif/else rules explicitly: do not push elseif or else as new stack frames. Instead require that the current top is an if. Allow many elseif but only one else per if — store an elseSeen flag on the if stack entry and set it on else; produce an error if else appears twice or if elseif/else appear when the top is not if.

Parsing and implementation tips: avoid while(!file.eof()) and operator>> for token-level parsing because you lose line boundaries and attached punctuation. Use getline() and scan characters so { and } attached to identifiers are still captured. Skip comments and string literals so braces inside them don't trigger false errors. Replace system("pause") and any unchecked s.top() usage with safe checks. Always print both the offending token and the original opener line to make fixes straightforward.

Minimal stack-item pattern (illustrative):

struct Item { std::string token; int line; bool elseSeen; };
std::stack<Item> st;

// when you see "if": st.push({"if", lineno, false});
// on "elseif"/"else": validate st.top().token == "if" and update elseSeen;
// on closers: check st.empty() then match st.top().token, pop or report.

Test with nested constructs, stray closers, repeated else, and files containing comments/strings to confirm robust behavior.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.