if/else语句中存在多个条件
Multiple conditions in if/else statement?
我还是个初学者,所以如果经常问这些问题,我很抱歉。我搜索了好几次,但都找不到合适的答案。以下是我的两个主要问题:
我正在构建一个简单的计数程序,允许用户按1、2、3等进行计数。首先,这里是我的函数代码:
int Count::numOne() {
cout << "You chose to count by 1! Press "Y" to continue counting. Press "N" to return to the main page." << endl;
while (cin >> yesNo) {
if ((yesNo == 'y') || (yesNo == 'Y')) {
++one;
cout << one << endl;
}
else if ((yesNo == 'n') || (yesNo == 'N')) {
cout << "User selected no." << endl; //How do I return back to the main function?
}
else {
cout << "Please enter either "Y" or "N"." << endl;
}
}
return 0;
}
我已经让程序在大部分情况下正常运行,但对于if/else条件,是否有"更好"或更干净的语法可供使用?我觉得
if ((yesNo == 'y') || (yesNo == 'Y'))
具有不必要的冗余并且可以更清洁。
此外,如果用户输入"n"或"n",我如何返回主函数并从头开始程序?
1)从编译代码的角度来看,进行这两个比较都很好,并且清楚地调用每个比较是非常可读的
2) 您想要的是一个break;
表达式来突破while循环
您想要类似以下内容:
string yes {"Yy"};
cout << "You chose to count by 1! Press "Y" to continue counting. Press "N" to return to the main page." << endl;
while (cin >> yesNo) {
if (yes.find_first_of(yesNo) != string::npos) {
++one;
cout << one << endl;
}
// ... other stuff
}
-
在这种情况下,
operator==
调用周围的括号是不必要的,请参阅运算符优先级。除非你想制作一个自定义的比较函数并使用它,否则这就是它的全部#include <cctype> // will accept both c and option as lowercase or uppercase bool isOption(char c, char option) { return std::tolower(c) == std::tolower(option); }
-
只是循环中的
break
,所以它是return
的0
,或者return
(可能是其他)值,因为你在一个函数中。
相关文章:
- 模板元图.班级成员的条件存在
- 如果检查和内联条件之间是否存在编译器差异
- __has_include() 和后续 #include 之间是否存在争用条件
- 对条件表达式结果的赋值(其中第二个和第三个操作数是相同类型和值类别的变量)是否仍然存在?
- 根据成员变量的类型是否存在,有条件地定义该变量
- 放置多个条件时,循环是否存在限制
- 标准::condition_variable 中可能存在的争用条件
- 具有 3 个条件的 if 语句(三角形存在)
- 如果存在条件,是否有更简单的表示形式
- 检查前提条件是否存在原子增量,即原子值小于指定值
- 当只有一个线程写入 c++ 中的布尔变量时,是否存在争用条件
- 如何在Visual C++中有条件地包含一个不存在的文件
- C++ - 测试是否存在 DLL 以有条件地运行某些函数
- 在C++中,是否存在在特定条件下定义/运行宏的问题
- 循环中存在多个条件
- 存在多个条件时"IF"语句中的执行顺序
- if/else语句中存在多个条件
- 有条件地初始化一个结构体字段——仅当它存在于该结构体中时
- 如何声明在条件块之间持久存在的引用变量
- 在or条件语句中是否存在强制对两个表达式求值的模式或技巧?