如何将cin和cout重定向到文件?

How to redirect cin and cout to files?(如何将cin和cout重定向到文件?)
本文介绍了如何将cin和cout重定向到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何将 cin 重定向到 in.txt 并将 cout 重定向到 out.txt?

How can I redirect cin to in.txt and cout to out.txt?

推荐答案

这是您想要执行的操作的示例.阅读注释以了解代码中每一行的作用.我已经在我的电脑上用 gcc 4.6.1 测试过它;它工作正常.

Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.

#include <iostream>
#include <fstream>
#include <string>

void f()
{
    std::string line;
    while(std::getline(std::cin, line))  //input from the file in.txt
    {
        std::cout << line << "
";   //output to the file out.txt
    }
}
int main()
{
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!

    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    std::string word;
    std::cin >> word;           //input from the file in.txt
    std::cout << word << "  ";  //output to the file out.txt

    f(); //call function


    std::cin.rdbuf(cinbuf);   //reset to standard input again
    std::cout.rdbuf(coutbuf); //reset to standard output again

    std::cin >> word;   //input from the standard input
    std::cout << word;  //output to the standard input
}

您可以在一行中保存重定向:

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect

此处 std::cin.rdbuf(in.rdbuf())std::cin's 缓冲区设置为 in.rdbuf()然后返回与 std::cin 关联的旧缓冲区.使用 std::cout 也可以做到同样的事情 —或任何.

Here std::cin.rdbuf(in.rdbuf()) sets std::cin's buffer to in.rdbuf() and then returns the old buffer associated with std::cin. The very same can be done with std::cout — or any stream for that matter.

希望有所帮助.

这篇关于如何将cin和cout重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
Is TCHAR still relevant?(TCHAR 仍然相关吗?)