无论在循环中输入了多少字符串,其他参数只出现一次

时间:2017-07-04 08:24:33

标签: c++

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    string input = " ";
    cout << "Do you wanted to input : " << endl << "a. String" << endl 
         << "b. Integer" << endl;
    while (input != "A" || input != "a" || input != "B" || input != "b")
    {
        cin >> setw(1) >> input;
        if (input == "A" || input == "a")
        {
            cout << "String" << endl; break;
        }
        else if (input == "B" || input == "b")
        {
            cout << "int" << endl; 
            break;
        }
        else
        {
            cout << "Please input only the given option." << endl;
        }
    }
}

所以,我现在正在使用我在那里发布的代码,我的问题是,当我通过输入多于1个字符串来触发else参数时,就像使用单词&#39; how多&#39;将导致else参数出现两次,如果我输入&#39; c d e&#39;当我只想要它只出现一次,无论输入多少字符串,它都会出现三次。我知道它可能与我错过的循环有关,但我不知道它是什么。有这个决心吗?我非常感谢您的帮助。非常感谢你

1 个答案:

答案 0 :(得分:0)

您可以使用while循环代替do while循环。实际上,您在每个成功分支后使用了break。因此,您甚至可以使用for (;;)循环(条件始终为真的无限循环)。

演示:

$ cat >test-input.cc <<EOF
> #include <iostream>
> #include <string>
> 
> using namespace std;
> 
> int main()
> {
>   cout
>     << "Please, choose an option:" << endl
>     << "a. String" << endl
>     << "b. int" << endl;
>   for (;;) {
>     string input; getline(cin, input);
>     if (input == "a" || input == "A") {
>       cout << "String" << endl;
>       break;
>     }
>     if (input == "b" || input == "B") {
>       cout << "int" << endl;
>       break;
>     }
>     cout << "Please, choose one of the options." << endl;
>   }
>   cout << "Well done." << endl;
>   return 0;
> }
> EOF

$ g++ -std=c++11 -o test-input test-input.cc

$ ./test-input.exe 
Please, choose an option:
a. String
b. int
abc
Please, choose one of the options.

Please, choose one of the options.
a
String
Well done.

$ ./test-input.exe 
Please, choose an option:
a. String
b. int
b
int
Well done.

$

注意:

  1. 我按Some programmer dude的建议将cin <<替换为getline()(我也不愿意)。

  2. 每个&#34;成功&#34;没有else ifbreak结尾(因此在这种情况下未达到以下声明)。这可以想象为&#34;隐含else&#34;。