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

Changing while loop to accommodate two situations

本文关键字:两种 情况 while 循环 改变      更新时间:2023-10-16

假设我有一个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()