How can I tell the program to stop using freopen

ε祈祈猫儿з 提交于 2021-02-17 02:50:28

问题


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

#include<stdio.h>

also known as:

#include<cstdio>

At some point in my program I tell the program to use the file de_facut.txt as an in file:

freopen("de_facut.txt","r",stdin);

How can I tell the program to use the console to put the input (as default) instead of the in file? First I want to read from that file, but later in the program I want the user to enter input in the console. I hope you understood my problem, I am not very good at english.


回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/33455716/how-can-i-tell-the-program-to-stop-using-freopen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!