【问题标题】:How to determine if a line from a input file is the last line? c++如何确定输入文件中的一行是否是最后一行? C++
【发布时间】:2017-03-28 14:39:30
【问题描述】:

我编写了一个程序来检查 .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;
                    }
                }
            }

【问题讨论】:

  • 很高兴知道完整的代码。这样,我们可以更好地为您的代码找到解决方案(当然,制作minimal reproducible example 会更好!)。现在,我们只能猜测您是如何阅读current,...因此无法提供好的解决方案。
  • eof 标志不会被设置,除非您尝试读取过去文件末尾。应该在documentation 中指出这一点。
  • 可能会一直读到最后并向后阅读,直到点击\n,然后ftell() 呼叫给你位置。每当你通过这个位置时,你就在最后一行。
  • @Rakete1111 我编辑了帖子。
  • @CinCout 是的,这是一次糟糕的尝试 :)

标签: c++ algorithm if-statement input eof


【解决方案1】:

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

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
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2016-08-17
    • 1970-01-01
    • 2012-06-20
    • 2021-06-29
    • 1970-01-01
    • 2016-03-20
    相关资源
    最近更新 更多