我最大的问题都是上面所说的,无法跳转到标签鳍(第27行出错),错误:从这里(第12和14行出错)和十字架初始化错误(第20行出错)请帮助!
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Please comply. y/n: ";
std::string answer;
std::cin >> answer;
if (answer == "y"){std::cout << "You were spared." << std::endl; goto fin;}
if (answer == "Miche"){std::cout << "The killers understood that you understood the prophecy, so they took you to their master" << std::endl; goto secret;}
if (answer == "n"){std::cout << "You were brutally killed." << std::endl; goto fin;}
else {std::cout << "You randomly babled " << answer << ", getting yourself killed."; goto fin;}
secret:
std::cout << "In order to fully find out if you are the legendary Miche, they took you to their leader."
<< " The master looked you over, and asked you one final question. The master asks you, fish?" << std::endl;
std::string fish; fish = "none";
std::cin >> fish;
if (fish == "fish."){std::cout << "You were put in the throne of the king, where you ruled your near killers and their species for eternity."
<< std::endl; goto fin;}
else {std::cout << "You failed and were immediately killed." << std::endl; goto fin;}
goto fin;
fin:
return 0;
}
答案 0 :(得分:4)
问题在于,基本上是这样的:
int main() {
if (whatever)
goto fin;
std::string fish;
fin:
return 0;
}
如果whatever
为真,则goto跳过fish
的构造。这是不允许的,因为编译器无法生成合理的代码来销毁fish
,具体取决于是否执行了goto。
解决方案:不要使用goto。
的可能性:
int main() {
if (whatever)
goto fin;
{
std::string fish;
}
fin:
return 0;
这里,fish
在块结束时被销毁,因此goto不会引起问题(除了其固有的非结构化特性)。
更好:
int main() {
if (!whatever) {
std::string fish;
}
return 0;
}
答案 1 :(得分:0)
您可以使用更简单的功能复制问题。
void foo()
{
goto fin;
std::string fish = "none";
std::cin >> fish;
fin:
}
为什么会出现问题?当执行跳转到fin:
时,不会执行初始化fish
的代码。函数返回时将调用它的析构函数。由于析构函数将在未初始化的对象上调用,因此程序将显示未定义的行为。
对您的问题最简单的解决方法是将main
中的几乎所有内容放入另一个函数中,然后使用return
代替goto
。
void do_stuff()
{
std::string name;
std::cout << "Please comply. y/n: ";
std::string answer;
std::cin >> answer;
if (answer == "y")
{
std::cout << "You were spared." << std::endl;
return;
}
if (answer == "n")
{
std::cout << "You were brutally killed." << std::endl;
return;
}
if (answer == "Miche")
{
std::cout << "The killers understood that you understood the prophecy, so they took you to their master" << std::endl;
}
else
{
std::cout << "You randomly babled " << answer << ", getting yourself killed.";
return;
}
std::cout << "In order to fully find out if you are the legendary Miche, they took you to their leader."
<< " The master looked you over, and asked you one final question. The master asks you, fish?" << std::endl;
std::string fish = "none";
std::cin >> fish;
if (fish == "fish")
{
std::cout << "You were put in the throne of the king, where you ruled your near killers and their species for eternity." << std::endl;
}
else
{
std::cout << "You failed and were immediately killed." << std::endl;
}
}
int main()
{
do_stuff();
}