所以我一直听说使用 goto 会让你变得很糟糕,所以直到最近我才真正尝试过它。为了好玩,我决定制作一个严重依赖 goto 语句的程序,以亲眼看看它们何时可以真正派上用场。
换句话说,我有意远离任何被普遍认为是好的编程的东西,并且我正在尝试其他方法...
话虽如此,我遇到了第一个问题。我想从一个文件中读取,并通过简单地将我收集的数据传输到我的代码的另一部分来模拟一个“函数”。运行它......然后返回到文件。
这是我的一些代码,因此您可以了解我正在尝试做的事情的基本概念:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string command, fileName, fileLine;
while (command != "quit")
{
cout << "cmd> ";
cin >> command;
if (command == "function")
{
FUNCTION: // I want to manipulate the data I gather from the file here.
cout << "Perform a certain task here instead of using a function." << endl;
goto FILE;
}
else if (command == "file")
{
cout << "filename> ";
cin >> fileName;
ifstream myFile(fileName.c_str());
if (myFile.is_open())
{
while (getline(myFile, fileLine))
{
goto FUNCTION;
FILE:
cout << "You finished your task using the above 'if' statement." << endl;
}
myFile.close();
}
}
else if (command == "quit")
break;
else
cout << "Invalid Command." << endl;
}
return 0;
}
当我尝试编译我的代码时,出现以下错误:
example.cpp: In function ‘int main()’:
example.cpp:37:6: error: jump to label ‘FILE’ [-fpermissive]
example.cpp:21:9: error: from here [-fpermissive]
example.cpp:29:13: error: crosses initialization of ‘std::ifstream myFile’
看来我不能使用goto 来跳过“ifstream myFile”的初始化。有谁知道我可以使用 goto 完成此任务的方法,无需使用函数且无需使用任何标志?
最佳答案
问题正如编译器告诉您的那样...您不能跳过 ifstream myFile(fileName.c_str());
的初始化,这正是您的 goto 语句试图完成的。如果您忽略该警告,您可能会在分配/初始化之前或释放之后使用 myFile
(这非常糟糕)。我建议您将 if (command == "function")
代码块移动到 else if (command == "file")
的范围内。
一些一般性建议:
1) goto 在 C 代码中大量用于清理。您可以浏览 linux 内核并查看大量示例 1 2 3
2) goto 在 C 中很糟糕,在 C++ 中更糟,因为在 C++ 中你有各种各样的隐式内存操作,你可以在 C 中轻松避免这些操作。所以也许你想在 C 中重写代码然后你会没有错误/警告。
关于c++ - 我如何使用 goto 来执行文件任务而不是使用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050341/