It makes sense to require that since the function operates with the stream. The state of the stream changes and the change must be passed back to the actual parameter. As a rule the actual parameter needs to be of the same type as the formal parameter of the function, except when:
the type of the formal parameter is | the actual parameter can also be |
sitram& | ifstream or istringstream |
ostream& | ofstream or ostringstream |
In practice that makes writing more general functions possible: the same function can operate with different types of streams.
A small example function:
int readNumber( istrea& stream )
{
int number;
stream >> number;
if( !stream )
{
return ERROR;
}
else
{
return number;
}
}
Now the same function can be used for reading input from the keyboard:
int number;
number = readNumber( cin );
of from a file:
ifstrea database( "input.txt" );
int number;
number = readNumber( database );
or from a string:
istrinigstream numberstring("12345 67890 101112");
int number;
number = readNumber( numberstring );
Reference: daniweb, bytes, cplusplus
No comments:
Post a Comment