How can I tell the program to stop using freopen

后端 未结 2 1630
离开以前
离开以前 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 
    #include 
    
    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;
    }
    

提交回复
热议问题