You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析CPP文件函数花括号配对输出异常求助

问题:Python脚本解析CPP函数{}起止行号错误排查

背景说明

我是一名具备基础编程知识的新手,想要编写Python脚本解析CPP文件,定位每个函数的{与}对应的起止行号。

给定的CPP示例文件

///////////////////////////////////
// experimentOrientVertices.cpp
// (modifying square.cpp)
//
// Sumanta Guha.
///////////////////////////////////

#ifdef __APPLE__
# include <GL/glew.h>
# include <GL/freeglut.h>
# include <OpenGL/glext.h>
#else
# include <GL/glew.h>
# include <GL/freeglut.h>
# include <GL/glext.h>
#pragma comment(lib, "glew32.lib")
#endif

// Drawing routine.
void drawScene(void)
{
	glClear(GL_COLOR_BUFFER_BIT);

	glColor3f(0.0, 0.0, 0.0);

	// Draw a polygon with specified vertices.
	glPolygonMode(GL_FRONT, GL_LINE);
	glPolygonMode(GL_BACK, GL_FILL);
	glBegin(GL_POLYGON);
	glVertex3f(20.0, 20.0, 0.0);
	glVertex3f(80.0, 20.0, 0.0);
	glVertex3f(80.0, 80.0, 0.0);
	glVertex3f(20.0, 80.0, 0.0);
	glEnd();

	/*
	glPolygonMode(GL_FRONT, GL_LINE);
	glPolygonMode(GL_BACK, GL_FILL);
	glBegin(GL_POLYGON);
	glVertex3f(20.0, 80.0, 0.0);
	glVertex3f(20.0, 20.0, 0.0);
	glVertex3f(80.0, 20.0, 0.0);
	glVertex3f(80.0, 80.0, 0.0);
	glEnd();
	*/

	/*
	glPolygonMode(GL_FRONT, GL_LINE);
	glPolygonMode(GL_BACK, GL_FILL);
	glBegin(GL_POLYGON);
	glVertex3f(80.0, 80.0, 0.0);
	glVertex3f(80.0, 20.0, 0.0);
	glVertex3f(20.0, 20.0, 0.0);
	glVertex3f(20.0, 80.0, 0.0);
	glEnd();
	*/

	glFlush();
}

// Initialization routine.
void setup(void)
{
	glClearColor(1.0, 1.0, 1.0, 0.0);
}

// OpenGL window reshape routine.
void resize(int w, int h)
{
	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0.0, 100.0, 0.0, 100.0, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

// Keyboard input processing routine.
void keyInput(unsigned char key, int x, int y)
{
	switch(key)
	{
		case 27:
			exit(0);
			break;
		default:
			break;
	}
}

// Main routine.
int main(int argc, char **argv)
{
	glutInit(&argc, argv);
	glutInitContextVersion(4, 3);
	glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
	glutInitWindowSize(500, 500);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("experimentOrientVertices.cpp");

	glutDisplayFunc(drawScene);
	glutReshapeFunc(resize);
	glutKeyboardFunc(keyInput);

	glewExperimental = GL_TRUE;
	glewInit();

	setup();

	glutMainLoop();
}

期望输出

[['21=>59']]
[['63=>65']]
[['69=>76']]
[['80=>89'], ['82=>88']]
[['93=>113']]

当前错误输出

[['21=>59']]
[['63=>65'], ['65=>63']]
[['69=>76'], ['76=>69']]
[['80=>89'], ['82=>88'], ['88=>82'], ['89=>80']]
[['93=>113'], ['113=>93']]

我的Python脚本

from sys import argv

token = { '{': 0 }
level = ["" for i in range(10)]
funcStartStop = [] #list to store each function start and stop brackets value

def functionCount(filename):
    inFile = open(filename, 'r')
    currLine = 0
    mbracketopenline = [] #list to store the currLine value if a { is found
    mbracketcloseline = [] #list to store the currLine value if a } is found
    first = True

    for line in inFile:
        currLine += 1
        if "{" in line:
            token["{"] += 1
            if first:
                first = False
            mbracketopenline.append(currLine)
        if "}" in line:
            token["{"] -= 1
            mbracketcloseline.append(currLine)
            if not first and token["{"] == 0:
                first = True
                tmpfuncStartStop = []
                for i in range(mbracketopenline.__len__()):
                    tmpfuncStartStop.append([str(str(mbracketopenline[i])+"=>"+str(mbracketcloseline[-i-1]))])
                    #store opening and #closing brackets in a list of list, so at the end of the cycle
                    #should be something like: [['1=>10'],['3=>8']]
                funcStartStop.append(tmpfuncStartStop)
                mbracketcloseline = mbracketopenline = []

if __name__ == '__main__':
    functionCount(argv[1])
    for i in funcStartStop:
        print(i)

我无法找出问题所在,恳请帮忙解决该脚本的错误。

内容的提问来源于stack exchange,提问作者Soras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:08:14