繁体   English   中英

如何告诉程序停止使用 freopen

[英]How can I tell the program to stop using freopen

我是 C++ 的初学者,我有一个超出我限制的问题。 我在 GNU GCC 下编译。 我用

#include<stdio.h>

也称为:

#include<cstdio>

在我的程序中的某个时刻,我告诉程序使用文件 de_facut.txt 作为 in 文件:

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

我怎么能告诉程序文件中使用控制台把输入(默认),而不是? 首先我想从该文件中读取,但稍后程序中我希望用户在控制台中输入输入。 我希望你理解我的问题,我不太擅长英语。

关于stdout也被问到了同样的问题: How to redirect the output back to the screen after freopen("out.txt", "a", stdout) ,但两者的答案是一样的 -没有干净的方法来做到这一点: http://c-faq.com/stdio/undofreopen.html

由于您确实需要稍后在程序中从控制台读取,我建议您只将文件作为文件打开。 如果您想使用stdin从文件中读取的原因是不必将文件句柄传递给fscanf函数,那么您可以考虑改用 fstream 工具 - 代码看起来与从控制台读取时完全一样:

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

使用fclose()

FILE *fp=freopen("data.txt","r",stdin);
/*your code here*/
fclose(fp);

参考: C 库函数 - freopen()

在窗户里,

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

这段代码对我有用。 它将标准输入切换到控制台。
PS:在此之前用于输入的文本文件,必须以换行符结束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM