How to redirect cin and cout to files?

后端 未结 5 1575
慢半拍i
慢半拍i 2020-11-22 07:24

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

5条回答
  •  余生分开走
    2020-11-22 07:44

    Here is a short code snippet for shadowing cin/cout useful for programming contests:

    #include 
    
    using namespace std;
    
    int main() {
        ifstream cin("input.txt");
        ofstream cout("output.txt");
    
        int a, b;   
        cin >> a >> b;
        cout << a + b << endl;
    }
    

    This gives additional benefit that plain fstreams are faster than synced stdio streams. But this works only for the scope of single function.

    Global cin/cout redirect can be written as:

    #include 
    
    using namespace std;
    
    void func() {
        int a, b;
        std::cin >> a >> b;
        std::cout << a + b << endl;
    }
    
    int main() {
        ifstream cin("input.txt");
        ofstream cout("output.txt");
    
        // optional performance optimizations    
        ios_base::sync_with_stdio(false);
        std::cin.tie(0);
    
        std::cin.rdbuf(cin.rdbuf());
        std::cout.rdbuf(cout.rdbuf());
    
        func();
    }
    

    Note that ios_base::sync_with_stdio also resets std::cin.rdbuf. So the order matters.

    See also Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

    Std io streams can also be easily shadowed for the scope of single file, which is useful for competitive programming:

    #include 
    
    using std::endl;
    
    std::ifstream cin("input.txt");
    std::ofstream cout("output.txt");
    
    int a, b;
    
    void read() {
        cin >> a >> b;
    }
    
    void write() {
        cout << a + b << endl;
    }
    
    int main() {
        read();
        write();
    }
    

    But in this case we have to pick std declarations one by one and avoid using namespace std; as it would give ambiguity error:

    error: reference to 'cin' is ambiguous
         cin >> a >> b;
         ^
    note: candidates are: 
    std::ifstream cin
        ifstream cin("input.txt");
                 ^
        In file test.cpp
    std::istream std::cin
        extern istream cin;  /// Linked to standard input
                       ^
    

    See also How do you properly use namespaces in C++?, Why is "using namespace std" considered bad practice? and How to resolve a name collision between a C++ namespace and a global function?

提交回复
热议问题