Question?

This is a discussion on Question? within the C++ Programming forums, part of the General Programming Boards category; I have to write a input function for a class. The function is suppose to readin the initial balance of ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    20

    Question?

    I have to write a input function for a class. The function is suppose to readin the initial balance of a bank account and the interest rate, but i have to have a perameter of type istream. My question is why would i do this and what do I do with the istream in the function.

  2. #2
    Open to suggestions Brighteyes's Avatar
    Join Date
    Mar 2003
    Posts
    204
    >My question is why would i do this and what do I do with the istream in the function.
    Because by taking an istream argument, you can read from stdin, or a file, or another input stream without changing the function. It would be done something like this
    Code:
    double readInitialBalance(istream& in)
    {
        if (!(in>> balance))
            throw someException("Wrong format");
    
        return balance;
    }
    p.s. What the alphabet would look like without q and r.

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    648
    Or, additionally you can overload the >> operator. Note: some compilers let you place the function's code with the friend definition. But this, is garanteed to work.
    Code:
    // in your class
    friend istream &operator >> (istream& in, BankAccount &acc);
    
    // in global code area
    istream &operator >> (istream& in, BankAccount &acc)
    {
        return in >> acc.balance >> acc.rate;
    }
    
    // usage:
    BankAccount ba;
    cin >> ba;

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    better as a non friend speedy. Illustrated several times before with code. do a search to see how if you want.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 03:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 06:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 01:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 10:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21