如何使输入字符串不是第一个字符?

时间:2015-10-18 13:09:31

标签: c++ string menu

我想创建一个既有字母又有数字的菜单。

我尝试使用字符串,但是现在当用户输入20时,它只会取第一个数字,即2.如何制作,当用户放20时,它将被视为20而不是2?

#include <iostream>

using namespace std;

int main ()
{
string choice;
cout << "1. A" << endl;
cout << "2. B" << endl;
cout << "3. C" << endl;
cout << "4. D" << endl;
cout << "Q. Quit" << endl;
do
{
    cout << "Please enter your choice: ";
    cin >> choice;
    if (choice[0] == '1')
    {
    cout << "1";
    } else if (choice[0] == '2')
    {
        cout << "2";
    }  else if (choice[0] == '3')
    {
        cout << "3";
    } else if (choice[0] == '4')
    {
        cout << "4";
    } else if (choice[0] == 'q' || choice[0] == 'Q')
    {
        cout << "q";
    } else {
            cout << "Please choose one of the menu above. " << endl;
    }        
} while (choice[0] != 1 && choice[0] != 2 && choice[0] != 3 && choice[0] != 4 && choice[0] != 'q');
return 0;
}

您还可以在http://cpp.sh/7ipv

看到我的代码

1 个答案:

答案 0 :(得分:0)

您的代码将20视为2,因为它只会看到输入的第一个字符。

试试这个:

#include <iostream>

using namespace std;

int main ()
{
    string choice;
    cout << "1. A" << endl;
    cout << "2. B" << endl;
    cout << "3. C" << endl;
    cout << "4. D" << endl;
    cout << "Q. Quit" << endl;
    do
    {
        cout << "Please enter your choice: ";
        cin >> choice;
        if (choice == "1")
        {
        cout << "1";
        } else if (choice == "2")
        {
            cout << "2";
        }  else if (choice == "3")
        {
            cout << "3";
        } else if (choice == "4")
        {
            cout << "4";
        } else if (choice == "q" || choice == "Q")
        {
            cout << "q";
        } else {
                cout << "Please choose one of the menu above. " << endl;
        }        
    } while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "q" && choice != "Q");
    return 0;
}