tags:

views:

191

answers:

2

For example:

ifstream input;
input.open("file.txt");
translateStream(input, cout);
input.close();

How to write function translateStream? void translateStream(XXXX input, YYYY output)? What are the types for input and output?

Thanks

+7  A: 

std::istream and std::ostream, respectively:

void translateStream(std::istream& pIn, std::ostream& pOut);

Example:

void translateStream(std::istream& pIn, std::ostream& pOut)
{
    // line for line "translation"
   std::string s;
   while (std::getline(pIn, s))
    {
        pOut << s << "\n";
    }
}
GMan
Remember to do the test after the read. Converted to make while loop work correctly.
Martin York
Oops, thanks, bad habit. You added the newline too :]
GMan
Note that the streams are passed by reference. They can also be passed by pointer, but not by value.
Thomas Matthews
A: 

While GMan's answer is entirely correct and reasonable, there is (at least) one other possibility that's worth considering. Depending on the sort of thing you're doing, it can be worthwhile to use iterators to refer to streams. In this case, your translate would probably be std::transform, with a functor you write to handle the actual character translation. For example, if you wanted to translate all the letters in one file to upper case, and write them to another file, you could do something like:

struct tr { 
    char operator()(char input) { return toupper((unsigned char)input); }
};

int main() {
    std::ifstream input("file.txt");
    input.skipws(false);
    std::transform(std::ifstream_iterator<char>(input), 
        std::ifstream_iterator<char>(),
        std::ostream_iterator<char>(std::cout, ""),
        tr());
    return 0;
}

This doesn't quite fit with the question exactly as you asked it, but it can be a worthwhile technique anyway.

Jerry Coffin