gpt4 book ai didi

c++ - 在 C++ 中执行一次序列的最佳方式

转载 作者:行者123 更新时间:2023-11-27 23:11:42 24 4
gpt4 key购买 nike

使用 C++ 让一个序列只运行一次的最佳方法可能是什么?例如,为了更清楚地说明我有一个程序,您需要在其中猜测一个字符串,如果用户输入 hint 我会显示该词的提示,但我只允许它一次...我目前正在这样做:

   bool hintLock = false;
...
if (guess == "hint"){
if (!hintLock){
cout << hint << endl;
hintLock = true;
}
else
cout << "I've given you the hint" << endl;
}

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

void main(){
string guess;
bool hintLock = false;
cout << "Guess one of StackExchange's best site: Type \"hint\" for hint" << endl << endl;
do{
cout << "Guess > ";
cin >> guess;

if (guess == "hint"){ // Here it is
if (!hintLock){
cout << hint << endl;
hintLock = true;
}
else
cout << "I've given you the hint" << endl;
}
}
while (guess != "stackoverflow");
cout << "You've got it right!" << endl;
}

有没有更好的声明来做到这一点?还是已经是最好的了?

最佳答案

我怀疑您要么过度分析了事情,要么没有充分描述真正的问题。从您发布的代码中,我看不出为什么您不应该将要执行的代码包装到一个函数中,然后只需调用该函数一次。

void blahBlah()
{
// blah blah
}

int main()
{
if (userInput == "hint")
blahBlah();
}

也许您的意思是在您的程序中有一个主循环,该循环一直执行到程序终止,并且在该循环中您接受来自用户的输入。允许用户请求提示,但在程序运行期间只能请求一次。第一次要求提示时,他们会得到提示,但随后他们不会。

我仍然相信简单胜于花哨(阅读:复杂)。为此,我开始在主循环之外设置一个 bool 范围,每次他们寻求帮助时你都会检查它:

int main()
{
bool displayedHint = false;

// program's main loop
for (bool endProgram = false; !endProgram; )
{
std::string command = getUserInput();
if (command == "hint")
{
if (displayedHint)
{
cout << "I already gave you a hint!\n";
}
else
{
displayHint();
displayedHint = true;
}
}
}
}

关于c++ - 在 C++ 中执行一次序列的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com