首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将cin和cout重定向到文件?

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

Stack Overflow用户
提问于 2012-04-14 10:19:20
回答 5查看 212.5K关注 0票数 169

如何将cin重定向到in.txt,将cout重定向到out.txt

EN

回答 5

Stack Overflow用户

发布于 2012-12-15 08:46:59

只需写

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

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

Stack Overflow用户

发布于 2016-07-21 20:56:01

下面是一个简短的代码片段,用于跟踪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;
}

这提供了额外的好处,即普通fstream比同步的stdio流更快。但这只适用于单个函数的范围。

全局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();
}

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

另请参阅Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

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

但在这种情况下,我们必须一个接一个地选择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
                   ^

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

票数 26
EN

Stack Overflow用户

发布于 2014-09-22 04:33:58

假设编译程序名称是x.exe,$是系统外壳或提示符

$ x <infile >outfile 

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

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10150468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档