adam
adam

Reputation: 489

How to use pass ifstream input in a function and output? C++

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

Upvotes: 1

Views: 1936

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490158

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.

Upvotes: 1

GManNickG
GManNickG

Reputation: 503913

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";
    }
}

Upvotes: 8

Related Questions