How can I tell the program to stop using freopen

后端 未结 2 1631
离开以前
离开以前 2021-01-26 19:25

I am beginner in C++ and I have a question that is beyond my limits. I compile under GNU GCC. I use

#include

also known as:

相关标签:
2条回答
  • 2021-01-26 19:50

    The same question has been asked about stdout: How to redirect the output back to the screen after freopen("out.txt", "a", stdout), but the answer is the same for both - there's no clean way of doing this: http://c-faq.com/stdio/undofreopen.html

    Since you do need to read from the console later in the program, I'd suggest you just open the file as, well, a file. If the reason you wanted to use stdin to read from a file is the convenience of not having to pass the file handle to functions like fscanf, you could consider using fstream facilities instead - the code can look exactly as when reading from the console:

    #include <iostream>
    #include <fstream>
    
    using namespace std;
    int main()
    {
        int x;
        cin >> x; // reading from console
        {
            ifstream cin("input.txt");
            cin >> x; // reading from file
        }
        cin >> x; // again from console
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-26 20:03

    In windows,

    freopen("CON","r",stdin);
    

    this code worked for me. It switches the stdin to console.
    P.S: The text file used to take input before this, must be ended with a newline.

    0 讨论(0)
提交回复
热议问题