1

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

ndim
  • 35,870
  • 12
  • 47
  • 57
adam
  • 489
  • 1
  • 4
  • 5

2 Answers2

8

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";
    }
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
GManNickG
  • 494,350
  • 52
  • 494
  • 543
1

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
  • 476,176
  • 80
  • 629
  • 1,111