亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將CIN和cout重定向到文件?

如何將CIN和cout重定向到文件?

C++
qq_笑_17 2019-07-08 16:44:18
如何將CIN和cout重定向到文件?我怎么才能重定向cin到in.txt和cout到out.txt?
查看完整描述

3 回答

?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

只管寫

#include <cstdio>#include <iostream>using namespace std;int main(){
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;}


查看完整回答
反對 回復 2019-07-08
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

下面是一個用于隱藏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;}

這提供了額外的好處,即普通的fStreams比同步的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..所以命令很重要。

另見IOS_base的意義:sync_with_stdio(False);cin.tie(NULL);

STDIO流對于單個文件的范圍也很容易隱藏,這對于有競爭力的編程非常有用:

#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
                   ^

另見如何正確使用C+中的命名空間?為什么“使用命名空間STD”被認為是不好的做法?如何解決C+命名空間與全局函數之間的名稱沖突?


查看完整回答
反對 回復 2019-07-08
  • 3 回答
  • 0 關注
  • 814 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號