【问题标题】:c++ input stream not waiting for input with extraction operator overloadc ++输入流不等待提取运算符重载的输入
【发布时间】:2010-06-12 01:19:07
【问题描述】:

这个问题让我很烦。它不等待输入,而是关闭。我一直试图弄清楚这一点。有什么想法吗?

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

【问题讨论】:

  • 哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!哎哟!不要从 istream 操作符内部进行“cout”输出。那简直是邪恶的。这让我头疼。
  • 你应该告诉我们你在哪里使用它。是cin &gt;&gt; an_account;吗?你能告诉我们更多代码吗?

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


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2013-12-15
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多