C++ file-redirection

前端 未结 4 1969
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 07:28

For faster input, I read that you can do file-redirection and include a file with the cin inputs already set.

In theory it should be used l

4条回答
  •  情话喂你
    2020-12-31 07:43

    In addition to original redirection >/ >> and <

    You can redirect std::cin and std::cout too.

    Like following:

    int main()
    {
        // Save original std::cin, std::cout
        std::streambuf *coutbuf = std::cout.rdbuf();
        std::streambuf *cinbuf = std::cin.rdbuf(); 
    
        std::ofstream out("outfile.txt");
        std::ifstream in("infile.txt");
    
        //Read from infile.txt using std::cin
        std::cin.rdbuf(in.rdbuf());
    
        //Write to outfile.txt through std::cout 
        std::cout.rdbuf(out.rdbuf());   
    
        std::string test;
        std::cin >> test;           //from infile.txt
        std::cout << test << "  "; //to outfile.txt
    
        //Restore back.
        std::cin.rdbuf(cinbuf);   
        std::cout.rdbuf(coutbuf); 
    
    }
    

提交回复
热议问题