zoukankan      html  css  js  c++  java
  • how-to-redirect-cin-and-cout-to-files

    #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
    }
  • 相关阅读:
    linux压缩命令
    常用正则表达式
    java23种设计模式
    程序员
    让程序猿离职的非钱原因
    PHP MVC 中的MODEL层
    CSS样式补充代码
    网页中插入背景音乐
    Window.document对象(2)
    Window.document对象(1)
  • 原文地址:https://www.cnblogs.com/xuxm2007/p/4646728.html
Copyright © 2011-2022 走看看