-
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.
-
>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;
}
-
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;
-
better as a non friend speedy. Illustrated several times before with code. do a search to see how if you want.