改变while循环以适应两种情况
Changing while loop to accommodate two situations
假设我有一个while循环,它依赖于两个单独的输入。在情形一中,while循环将取值1,而在情形二中,它应该取值!有什么方法可以让我更有效率地做这件事吗?更简洁:
string hello;
cin >> hello;
if(hello == "one")
{
//make the while loop depend on value 1
}
else if(hello == "two")
{
//make the while loop depend on value !cin.eof()
}
while(/*depends on above conditional*/)
{}
我不想做这样的事情:
if(hello == "one)
{
while(1){}
}
else if(hello == "two")
{
while(!cin.eof){}
}
因为while循环基本上在每种情况下都做同样的事情
为了可读性和内聚性,我认为你应该把循环的内容移到一个单独的函数中:
void DoSomething() { /* ... */ }
// ...
if(hello == "one)
{
while(1){ DoSomething(); }
}
else if(hello == "two")
{
while(!cin.eof){ DoSomething(); }
}
很容易看出不同的while
循环在做同样的事情,但它们的条件不同。
我相信你在寻找这样的东西:
while((hello == "one") || (hello == "two" && !cin.eof)) {
}
这段代码会做你想要的,因为它检查'是变量"one"?如果是,继续执行。如果不是,它将检查:变量是否为"2"?如果是,它将检查cin.eof
。
如果两者都不是,则循环不会执行。(省略了第一个条件中的&& 1
,因为它总是'true',相等且无限循环)
为了简化,您可能需要考虑以下代码(如注释中建议的那样):
bool HelloIsOne = (strcmp(hello, "one") == 0);
bool HelloIsTwo = (strcmp(hello, "two") == 0);
while(HelloIsOne || HelloIsTwo && !cin.eof) {
}
我在前面的例子中放置的括号实际上是不必要的,因为&&
的绑定比||
强,但是它们有助于代码的总体清晰度。
直接使用or (||
)作为while循环的条件。设置第一个条件if(hello == "one")
。现在你有了一个while循环,如果其中一个条件是true
,它将循环。
bool value = hello == "one";
while (value || !cin.eof) {}
如果使用c++ 11:
#include <functional>
auto check = (hello == "one") ? []() bool -> { return 1; } :
[]() bool -> { return !cin.eof(); };
while(check) {
};
这个怎么样:
switch(hello)
{
case 'one':
{
for(; 1; );
{
// your loop here
}
break;
}
case 'two':
{
for(;!cin.eof; )
{
// your other loop here
}
break;
}
default:
{
cout << " shouldnt get here unless bad user input" << endl;
break;
}
}
你可以这样做:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string hello;
cin >> hello;
while(hello=="one"?1:(!cin.eof()))
{
//do stuff
}
return 0;
}
检查字符串hello
是否为"1",如果为真,则while
的条件为1
,否则按您的要求为!cin.eof()
。
相关文章:
- 两种情况下的输出不应该相同吗?
- 在没有堆的情况下用两种方法构造对象
- 为什么'const'在这两种情况下的行为不同?
- switch语句,两种类似情况不同
- 在两种情况下,铸造的工作方式不同
- 如果ConstexPR似乎仅在两种情况有效时起作用
- StrcMP的两种情况
- 程序在没有调试符号的情况下崩溃,运行良好(两种情况下都没有优化或任何内容)
- 为什么在使用C++模板的这两种情况下会出现差异
- c在这两种情况下是如何工作的以及有什么不同
- 为什么两种情况下的行为不同1.int i=1,2,3;和第二.int i;i=1,2,3;
- C++ 开关结构(运行最后一种情况两次)
- 为什么两种情况下数组的大小都不相同
- 两种情况下wchart字符积分值的差异
- c++:我应该如何重新安排这段代码,以便循环检查两种情况
- 检查string是否是有效的整数或小数(正负两种情况)
- 关于声明/发布IplImages的两种情况
- 添加字符串的这两种情况的区别是什么?
- 为什么sizeof(数组)在这两种情况下不同
- 改变while循环以适应两种情况