循环C++ 'else'
C++ 'else' in loops
在C++中,我在执行循环时遇到了一个问题。我只知道我在工作中忽略了一个明显的解决方案。这里有一个例子可供参考:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string loop();
int main()
{
string answer;
do
{
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or non";
loop();
}
}while (answer == "yes" || answer == "Yes" || answer == "YES");
return 0;
}
string loop()
{
string answer;
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO")
cout << "As you wish";
else if (answer == "yes" || answer == "Yes" || answer == "YES")
cout << "";
else
{
cout << "You didn't answer yes or non";
loop();
}
return answer;
}
当我在循环中执行If else时,当涉及到else
部分时,我遇到了一个问题。我似乎不知道如何显示告诉用户有错误的东西,然后重新运行相同的序列。例如,在我包含的程序中,当用户输入"是"或"否"以外的内容时,我不确定如何显示错误语句,然后将其循环回顶部,以便它再次提问。
您应该使用while循环。
string answer;
while ( (answer != "yes") && (answer != "no") ) {
cout << "Do you wish to be asked this question again?: ";
cin >> answer;
if (answer == "no" || answer == "No" || answer == "NO") {
cout << "As you wish";
break;
}
if (answer == "yes" || answer == "Yes" || answer == "YES") {
cout << "";
break;
}
}
问题不在于循环;问题是你把逻辑搞得一团糟。解决方案不是修复循环的方法,而是理顺逻辑的方法。
一个比看起来有用得多的简单技巧是将循环与你在循环中所做的事情完全分离:
// This function does something, then returns a boolean value
// to indicate whether or not you should continue looping.
bool do_something();
int main()
{
bool continue_looping = true;
while (continue_looping) {
continue_looping = do_something();
}
}
现在,您实现do_something()
的方式不必担心实际执行循环;在这方面,它唯一的责任是返回一个值,指示循环是否应该继续。
您只需要一个do-while循环。。。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string ans{""};
transform(ans.begin(), ans.end(), ans.begin(), ::tolower); // convert string to lower case
do {
cout << "Do you wish to be asked this question again? ";
cin >> ans;
if (ans == "no") {
cout << "As you wish.";
} else
if (ans == "yes") {
cout << "";
}
else {
cout << "You didn't answer yes or no." << endl;
}
} while (ans != "yes" && ans != "no");
return 0;
}
注意,转换算法将字符串转换为小写,以避免yes和no的拼写变化。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- c++ std::enable_if .... else?
- 如果 else 语句不断循环
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 为什么我的最后一个 ELSE 条件无法正确执行
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 如果 else 语句使用大写和小写字母
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 多个'if'语句,不带'else'