【发布时间】: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