2

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

#include<stdio.h>

也称为:

#include<cstdio>

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

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

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

4

3 回答 3

3

关于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;
}
于 2015-10-31T20:26:07.043 回答
2

使用fclose()

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

ref: C 库函数 - freopen()

于 2021-05-08T11:23:16.073 回答
0

在窗户里,

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

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

于 2020-11-24T10:09:16.497 回答