在方法getline c ++之后,switch语句反应错误

时间:2015-01-12 12:10:28

标签: c++ class methods switch-statement do-while

我正在为大学编写一个银行应用程序,我偶然发现了一个问题。让我们以我的班级客户的方法为例。

void Customer::create_customer_data() {
    cout << "Client' Address: ";
    getline(cin, clientAddress);
    cin.ignore();
    cout << "Client's birth date: ";
    getline(cin, clientBirthDate);
    cin.ignore();
    cout << "Client's telephone number: ";
    getline(cin, clientTelephoneNumber);
    cin.ignore();
    cin.clear(); }

在main函数中,我有一个switch语句来处理用户选择。

int main() {
int choice, _globalClientNumber = 0;
Customer a(_globalClientNumber);
cout << "Welcome to bank manager 1.0!" << endl;

do {
    cout << "Main Menu"<< endl;
    cout << "Create a new customer (1)" << endl;
    cout << "Create a new account (2)" << endl;
    cout << "Cash money into account (3)" << endl;
    cout << "Cash money out of account (4)" << endl;
    cout << "Transfer money between two accounts (5)" << endl;
    cout << "See current status of a customer and its accounts (6)" << endl;
    cout << "End Application (0)" << endl;

    cout << "Choice: ";
    cin >> choice;

    switch (choice) {
        case 1:
            a.create_customer_data();
            break;
        case 2:
            a.create_new_account();
            break;
        case 3:
            a.cash_in();
            break;
        case 4:
            a.cash_out();
            break;
        case 5:
            a.transfer_money();
            break;
        case 6:
            a.print();
            break;
        default:
            break;
    }

    cout << endl;
}
while (choice != 0);

return 0; }

我一直存在的问题是do_ while循环正在处理create_customer_data方法在屏幕上写入的值。因此,如果create_customer_data中的clientTelephoneNumber不以0结尾,则主菜单会由do-while循环显示两次。如果有人能告诉我我的错误在哪里,我将不胜感激。

编辑:简短地说:选择变量被覆盖,do-while循环再次执行,导致双重打印菜单。

1 个答案:

答案 0 :(得分:1)

我想说,你的cin需要刷新。

答案可以在这里找到: How do I flush the cin buffer?