更改while循环以适应两种情况

时间:2013-03-27 20:35:27

标签: c++

假设我有一个依赖于两个独立输入的while循环。在情境一中,while循环将取值1,而在情境二中,它应该取!cin.eof()。有没有办法可以有效地做到这一点?更简洁:

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循环在每种情况下基本上都做同样的事情。

6 个答案:

答案 0 :(得分:3)

为了便于阅读并且为了cohesion的利益,我认为您应该将循环的内容移动到一个单独的函数中:

void DoSomething() { /* ... */ }

// ...
if(hello == "one)
{
    while(1){ DoSomething(); }
}
else if(hello == "two")
{
    while(!cin.eof){ DoSomething(); }
}

更容易看出不同的while循环正在做同样的事情,但它们的条件不同。

答案 1 :(得分:2)

只需使用或(||)作为while循环中的条件。设置第一个条件if(hello == "one")。现在你有一个while循环,如果其中一个条件是true,它将循环。

bool value = hello == "one";
while (value || !cin.eof) {}

答案 2 :(得分:2)

我相信你正在寻找这样的东西:

while((hello == "one") || (hello == "two" && !cin.eof)) {
}

这段代码会做你想要的,因为它检查'是变量“一”?如果是这样,继续执行。如果不是,它会检查:变量是“两个”吗?如果是,则会检查cin.eof

如果不是,则循环不会执行。 (省略了第一个条件中的&& 1,因为它总是'真',等于和无限循环)

编辑:

为简化起见,您可能需要考虑此代码(如评论中所示):

bool HelloIsOne = (strcmp(hello, "one") == 0);
bool HelloIsTwo = (strcmp(hello, "two") == 0);

while(HelloIsOne || HelloIsTwo && !cin.eof) {
}

我在上一个示例中放置的括号实际上是不必要的,因为&&绑定比||强,但它们有助于代码的一般清晰度。

答案 3 :(得分:0)

如果您使用的是C ++ 11:

#include <functional>

auto check = (hello == "one") ? []() bool -> { return 1; } :
                                []() bool -> { return !cin.eof(); };
while(check) {
};

答案 4 :(得分:0)

这个怎么样:

    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;
        }
    }

答案 5 :(得分:-1)

您可以这样做:

#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()