如何使用bool sentinel值来结束C ++中的while循环?

时间:2016-07-27 12:16:44

标签: c++ loops while-loop boolean

我无法使用END的bool值来停止运行循环(下面的代码)。程序的其余部分可以工作,但是当我输入end时,我似乎无法停止循环。有什么建议吗?

bool END = false;
while (!END)
{
    cout << "Please enter a song or END to terminate: ";
    getline(cin, track);

    results = binarySearch(tracks, numTracks, track);

    if (results == -1)
        cout << track << " is not on the set list.\n";
    else if (results != -1)
    {
        cout << track << " is on the set list.\n";
    }
}

2 个答案:

答案 0 :(得分:3)

if ( track == "END" )
     break;// or whatever you want to happen, e.g. END = true

您需要检查用户输入。

答案 1 :(得分:3)

实际上,没有必要使用带有bool变量的while循环作为条件。您可以通过以下方式重写循环

while ( true )
{
    cout << "Please enter a song or END to terminate: ";

    if ( !getline( cin, track ) || track == "END" ) break;

    results = binarySearch(tracks, numTracks, track);

    if ( results == -1 )
    {
        cout << track << " is not on the set list.\n";
    }
    else
    {
        cout << track << " is on the set list.\n";
    }
}

还要注意if-else语句的else部分。