【发布时间】:2016-08-05 11:02:08
【问题描述】:
我正在编写我的第一个程序,它从文件中读取并允许您玩游戏,有人告诉我 exit 功能不是一个好主意。
我正在尝试回调 main 以正确关闭程序,但我收到以下错误:
C3861 'main':未找到标识符。
有什么想法我哪里出错了,或者我如何正确调用主函数?
代码如下:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void extra() {
int lives = 3;
int UI, intAnswer;
int opt = 0;
string IN, NoQ, q, c1, c2, c3, Answer;
fstream quiz;
cout << "Welcome to the guessing game!" << endl;
quiz.open("QuizQuestions.txt");
getline(quiz, IN);
cout << "There are " << IN << " Questions" << endl;
while (quiz.good() && opt !=2) {
getline(quiz, q);
cout << "Question " << q << endl;
getline(quiz, c1);
cout << c1 << endl;
getline(quiz, c2);
cout << c2 << endl;
getline(quiz, c3);
cout << c3 << endl;
getline(quiz, Answer);
intAnswer = stoi(Answer);
cout << "What answer do you think it is? ";
cin >> UI;
if (UI == intAnswer) {
lives++;
cout << "You got it right! You now have " << lives << " lives left " << endl << endl;
//i = 0;
}
else {
cout << "You got the answer wrong sorry, the correct answer is " << Answer << endl;
lives--;
cout << "You now have " << lives << " lives" << endl;
//i = 0;
if (lives < 1) {
cout << "You lose, would you like to play again? 1 for yes, 2 for no? ";
cin >> opt;
if (opt = 1) {
cout << endl;
extra();
}
else if (opt = 2) {
quiz.close();
return;
}
}
}
}
quiz.close();
}
int main() {
int UI;
cout << "Would you like to do the quiz? 1 - yes other - no ";
cin >> UI;
if (UI = 1) {
extra();
}
return 0;
}
【问题讨论】:
-
我会重新考虑你重玩游戏的方式。为什么不将整个游戏放入一个无限循环,然后在用户想要退出时打破该循环?这样你就不需要再次调用 extra() 函数,再次加载问题等等。另外,当 extra() 函数完成时,它将继续执行 main() 函数,该函数将顺利退出并返回“0”; .
-
请注意,
main中的if (UI = 1) extra();将始终调用extra()。测试应该是if (UI == 1)。 -
@PeteBecker 这就是我的问题所在!
-
@Tylv 我的意思是不能低估侦探技能的重要性。 Any C 运算符引用说明了赋值和相等之间的区别。并不是说这是一个“愚蠢”的问题——不是,问这个问题是完全合理的。本质上,它在任何 C 教程/参考资料中都很容易发现,而且对于诸如此类的问题,SO 是相对无情的。您有责任进行研究,在这种情况下,这很容易做到。如果不是,我建议现在查找参考资源,以便以后出现类似问题时参考。祝你好运!