c++ - 方法 getline c++ 后 Switch 语句 react 错误

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

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

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(); }

在主函数中,我有一个处理用户选择的 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; }

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

编辑:简而言之:choice 变量被覆盖,do-while 循环再次执行,导致菜单重复打印。

最佳答案

我会说,您的 cin 需要刷新。

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

关于c++ - 方法 getline c++ 后 Switch 语句 react 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901692/

相关文章:

java - 当有 if 且没有 else 时在 java 中返回值

java - 定义一个没有任何抽象方法的抽象类

java - 如果数据库包含现有数据,如何仅在 Activity 中调用一次方法?

c++ - C++中的电子邮件爬虫

c++ - CButton CDC::SetBkColor 什么都不做?

html - 悬停时删除CSS中的圆圈

C++ 包含 vs 前向声明策略

css - Angular UI 网格 : Conditional Row Format Not Overriding Default Alternating Colours

c++ - 模板问题 ('typename' 因为不是模板函数参数)

c++ - 英特尔® IPP 异步 C/C++ 库是否包含在标准 IPP 库中?