c ++输入流不等待具有提取运算符重载的输入

时间:2010-06-12 01:19:08

标签: c++ operator-overloading extraction operator-keyword

这个问题让我烦恼。它只是关闭而不是等待输入。我一直试图解决这个问题一段时间了。有什么想法吗?

    istream& operator>>(istream& is, Account &a) {
    cout << "Enter an accoutn number: ";
        is >> a.accountNo;
        cout << endl;
    cout << "Balance: ";
        is >> a.bal;
    return is;
    }

1 个答案:

答案 0 :(得分:1)

当我把它放到下面的程序中时,它工作正常(但如果你试图从std::cin以外的任何东西读取帐户,它将无法正常工作):

#include <iostream>

struct Account { 
    int accountNo;
    int bal;
};

using std::ostream;
using std::istream;
using std::cout;
using std::endl;

istream& operator>>(istream& is, Account &a) {
    cout << "Enter an account number: ";
    is >> a.accountNo;
    cout << endl;
    cout << "Balance: ";
    is >> a.bal;
    return is;
}

ostream &operator<<(ostream &os, Account const &a) { 
    return os << "Account #: " << a.accountNo << "\tBalance: " << a.bal;
}

int main() { 
    Account a;
    std::cin >> a;

    std::cout << a;
    return 0;
}