如何确定输入文件中的一行是否是最后一行? 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 条件就可以解决这个问题。如果你需要的话,我稍后可以post代码。
编辑:根据要求提供了较大的代码片段。 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
}
}
如果您不喜欢指针比较,可以使用迭代器版本:)
我编写了一个程序来检查 .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 条件就可以解决这个问题。如果你需要的话,我稍后可以post代码。
编辑:根据要求提供了较大的代码片段。 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
}
}
如果您不喜欢指针比较,可以使用迭代器版本:)