繁体   English   中英

如何确定输入文件中的一行是否为最后一行? C ++

[英]How to determine if a line from a input file is the last line? c++

我编写了一个程序来检查.cpp文件中是否有大括号。 该程序运行良好,找到语法错​​误,显示有问题的行号,然后退出。

但是,如果错误在输入cpp文件的最后一行,我必须显示不同的错误消息。

我试图按照以下方式实施它,但我认为这是错误的。 无论如何它是行不通的:)

else
                {
                    if(current == inputFile.eof()) //THIS IS WHAT I TRIED
                    {
                        cout << "Syntax error at the end of the program.";
                    }
                    else
                    {
                        cout << "Syntax error in line: " << current << "\n";
                        errorFound == true;
                    }
                }

我没有给出完整的代码,因为我认为带有正确变量的简单if条件可以解决此问题。 如果需要,我可以稍后发布代码。

编辑:较大部分的代码是按要求给出的。 counter是一个int变量,由counter ++每行更新一次。

for(int i = 0; i < line.length(); i++)
        {
            if (line[i] == '{')
            {
                stack.push(current);
            }
            else if(line[i] == '}')
            {
                if (!stack.isEmpty())
                {
                    stack.pop(opening);
                    cout << "Code block: " << opening << " - " << current << "\n";
                }
                else
                {
                    if(current == inputFile.eof())
                    {
                        cout << "Syntax error at the end of the program.";
                    }
                    else
                    {
                        cout << "Syntax error in line: " << current << "\n";
                        errorFound == true;
                    }
                }
            }

这是我能想到的最佳解决方案。 可能有更好的选择。

std::ifstream input_file{ "file.txt };
std::vector<std::string> contents;

// fill vector with file contents
std::string cline;
while (std::getline(input_file, cline))
    contents.push_back(cline);

// now loop
for (const auto& line : contents) {
    //...
    if (&line == &contents.back()) {
        // do something at the end of file
    }
}

如果您不喜欢指针比较,可以使用迭代器版本:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM