检测语言中平衡符号的程序

/* 检测语言中平衡符号的程序 
 * 例如:注释、小括号 
 */ 
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

bool zhuShi=false;
int leftXiao=0;
int rightXiao=0;    
bool shuchuXiao=false;    

//检测注释符号是否合理(/**/) 
void checkZhuShi(const char* p)
{
    while(*p!='\0')
    {
        if(*p=='/')
        {
            if(*++p=='*')
            {
                zhuShi=true;
                ++p;
            }
        }
        else if(*p=='*')
        {
            if(*++p=='/')
            {
                if(zhuShi==true)
                {
                    zhuShi=false;
                    ++p;
                }
                else
                {
                    cout << "no paired /**/\n";
                    return;
                }    
            }
        }
        else
               ++p;
    }
}

//检测小括号是否成对(()) 
void checkXiao(const char* p)
{
    while(*p!='\0')
    {
        if(*p=='(')
            ++leftXiao;
        else if(*p==')')
        {
            ++rightXiao;
            if(rightXiao>leftXiao)
            {
                cout << "no paired ()\n";
                shuchuXiao=true;                
            }            
        }
        ++p;
    }
}

//驱动程序 :读取文件中的字符串并检测 
void quDong(string filename)
{
    ifstream is{filename};
    string s;
    if(is)
    {
        while(getline(is,s))
        {
            checkZhuShi(s.c_str());    
            checkXiao(s.c_str());    
        }
        if(leftXiao!=rightXiao && shuchuXiao==false)
             cout << "no paired ()\n";
        is.close();
    }
    else
        cerr << "couldn't open file\n";
}

int main()
{
    string filename;
    cout << "Enter the filename:" << endl;
    cin >> filename;
    
    quDong(filename);
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lhb666aboluo/p/12787174.html