C++ 如何将cin和cout重定向到文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10150468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:40:04  来源:igfitidea点击:

How to redirect cin and cout to files?

c++

提问by updogliu

How can I redirect cinto in.txtand coutto out.txt?

我怎样才能重定向cinin.txtcoutout.txt

回答by Nawaz

Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.

这是您想要做什么的工作示例。阅读注释以了解代码中每一行的作用。我已经在我的电脑上用 gcc 4.6.1 测试过它;它工作正常。

#include <iostream>
#include <fstream>
#include <string>

void f()
{
    std::string line;
    while(std::getline(std::cin, line))  //input from the file in.txt
    {
        std::cout << line << "\n";   //output to the file out.txt
    }
}
int main()
{
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!

    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    std::string word;
    std::cin >> word;           //input from the file in.txt
    std::cout << word << "  ";  //output to the file out.txt

    f(); //call function


    std::cin.rdbuf(cinbuf);   //reset to standard input again
    std::cout.rdbuf(coutbuf); //reset to standard output again

    std::cin >> word;   //input from the standard input
    std::cout << word;  //output to the standard input
}

You could saveand redirectin just one line as:

您可以在一行中保存重定向为:

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect

Here std::cin.rdbuf(in.rdbuf())sets std::cin'sbuffer to in.rdbuf()and then returns the old buffer associated with std::cin. The very same can be done with std::cout— or any streamfor that matter.

这里std::cin.rdbuf(in.rdbuf())std::cin's缓冲区设置为in.rdbuf(),然后返回与 关联的旧缓冲区std::cin。可以用std::cout- 或任何来完成同样的事情。

Hope that helps.

希望有帮助。

回答by Tsotne Tabidze

Just write

写就好了

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

回答by Vadzim

Here is a short code snippet for shadowing cin/cout useful for programming contests:

下面是一段用于屏蔽 cin/cout 的简短代码片段,对编程竞赛很有用:

#include <bits/stdc++.h>

using namespace std;

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}

This gives additional benefit that plain fstreams are faster than synced stdio streams. But this works only for the scope of single function.

这提供了额外的好处,即普通 fstreams 比同步 stdio 流更快。但这仅适用于单个功能的范围。

Global cin/cout redirect can be written as:

全局 cin/cout 重定向可以写成:

#include <bits/stdc++.h>

using namespace std;

void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);

    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());

    func();
}

Note that ios_base::sync_with_stdioalso resets std::cin.rdbuf. So the order matters.

请注意,ios_base::sync_with_stdio也会重置std::cin.rdbuf. 所以顺序很重要。

See also Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

另请参阅ios_base::sync_with_stdio(false) 的重要性;cin.tie(NULL);

Std io streams can also be easily shadowed for the scope of single file, which is useful for competitive programming:

Std io 流也可以很容易地在单个文件的范围内隐藏,这对于竞争性编程很有用:

#include <bits/stdc++.h>

using std::endl;

std::ifstream cin("input.txt");
std::ofstream cout("output.txt");

int a, b;

void read() {
    cin >> a >> b;
}

void write() {
    cout << a + b << endl;
}

int main() {
    read();
    write();
}

But in this case we have to pick stddeclarations one by one and avoid using namespace std;as it would give ambiguity error:

但在这种情况下,我们必须std一一选择声明并避免,using namespace std;因为它会产生歧义错误:

error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^

See also How do you properly use namespaces in C++?, Why is "using namespace std" considered bad practice?and How to resolve a name collision between a C++ namespace and a global function?

另请参阅如何在 C++ 中正确使用命名空间?为什么“使用命名空间标准”被认为是不好的做法?以及如何解决 C++ 命名空间和全局函数之间的名称冲突?

回答by Ahmed Eid

assuming your compiles prog name is x.exe and $ is the system shell or prompt

假设您的编译程序名称是 x.exe 并且 $ 是系统外壳或提示

$ x <infile >outfile 

will take input from infile and will output to outfile .

将从 infile 获取输入并将输出到 outfile 。

回答by HaSeeB MiR

Try this to redirect coutto file.

试试这个将cout重定向到文件。

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

阅读全文使用 std::rdbuf 重定向 cin 和 cout