简体   繁体   English

如何在函数和输出中使用pass ifstream输入? C ++

[英]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? 如何编写函数translateStream? void translateStream(XXXX input, YYYY output) ? void translateStream(XXXX input, YYYY output) What are the types for input and output? 输入和输出的类型是什么?

Thanks 谢谢

std::istream and std::ostream , respectively: std::istreamstd::ostream分别为:

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

While GMan's answer is entirely correct and reasonable, there is (at least) one other possibility that's worth considering. 尽管GMan的答案是完全正确和合理的,但(至少)还有另一种可能性值得考虑。 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. 在这种情况下,您的translate可能是std::transform ,您编写的函子可以处理实际的字符翻译。 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. 这与您提出的问题并不完全相符,但是无论如何它都是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM