文件分析器-如何读取行

File Parser - How to Read Lines

本文关键字:读取 何读取 分析器 文件      更新时间:2023-10-16

我正试图在OpenGL中从stdin实现一个行扫描转换,该转换列出了行端点,如下所示:

L 0, 0, 150, 150
C 200 300
L -20, 40, 22, 55
[...]
Z

其中,[…]基本相同,Z字符是一个方便的终止运算符,尽管文件结尾也可以。L和C表示将分别用于绘制线/圆的点/数据集。

以下是我正在进行的解析器(包括所有正在使用的函数的库):

void parseFile ()
{
ifstream lines;
lines.open("C:/Users/Me/Desktop/lines.txt");
string currentLine = 0;
while(getline(lines, currentLine))
{
    switch(currentLine[0] = 'L')
    {
    string coordLine = currentLine.substr(1, currentLine.length());
    while (getline(lines, coordLine, ',')){
        for(int i = 0; i < coordLine.length(); i++) {
            char* c = 0;
            *(c+i) = coordLine[i];
            atoi(c);
            cout << c;
        }
        return;
    }
    }
    switch(currentLine[0] = 'Z') {
    break;
    }
    switch(currentLine[0] = 'C') {
    //Similar implementation to line case when resolved
    }
}
}

我试图将整数值(无逗号和L/C/Z分隔符)读取到数组中,这样我就可以简单地使用它们在OpenGL中绘图。然而,我在阅读和储存方面遇到了一些困难。正如你所看到的,我的算法方法是根据行首的字母字符进行切换,然后将字符串减少到剩余值,并尝试处理它们。然而,我在尝试将我定义的坐标线中的值转换为整数时遇到了困难。

简而言之,我的问题是:我的方法有意义吗?有什么可能比我计划实现的单独阵列方法更简单的方法来存储这些坐标以供OpenGL绘图使用?最后,如何将文件中的行转换为适当的整数进行存储?

当前代码存在许多问题。我提供了一个如何解析的例子:

void parseFile()
{
    ifstream lines;
    lines.open("test.txt");
    string currentLine; // Do NOT make this = 0 it will cause a crash!
    while(getline(lines, currentLine))
    {
        // no need to process blank lines
        // this also fixes potential crash
        // when you check the first character
        if(currentLine.empty())
            continue;
        // recommend std::stringstream for parsing strings
        std::istringstream iss(currentLine); // turn line into stream
        char type; // L, C or Z
        if(!(iss >> type)) // ALWAYS check for errors
            continue;
        // Your switch was incorrectly formed
        switch(type)
        {
            case 'L':
            {
                char comma;
                int x0, y0, x1, y1;
                // read the numbers skipping the commas
                if(!(iss >> x0 >> comma >> y0 >> comma >> x1 >> comma >> y1))
                {
                    // ALWAYS check for errors
                    std::cerr << "ERROR: Failed to read L: " << currentLine << std::endl;
                    continue;
                }
                // do something with coordinates (x0, y0, x1, y1) here
                std::cout << "(" << x0 << ", " << y0 << ", " << x1 << ", " << y1 << ")" << 'n';
                break;
            }
            case 'C':
            {
                break;
            }
            case 'Z':
            {
                break;
            }
            default:
                std::cerr << "ERROR: Unrecognized type: " << currentLine << std::endl;
        }
    }
}

注意:不要把错误检查当作事后考虑。

希望能有所帮助。