第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

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

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

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

3 回答

?
溫溫醬

TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊

只管寫(xiě)

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


查看完整回答
反對(duì) 回復(fù) 2019-07-08
?
ibeautiful

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊

下面是一個(gè)用于隱藏CIN/cout的簡(jiǎn)短代碼片段,用于編程競(jìng)賽:

#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流更快。但這只適用于單個(gè)函數(shù)的范圍。

全局CIN/Cout重定向可以寫(xiě)為:

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

請(qǐng)注意ios_base::sync_with_stdio還重置std::cin.rdbuf..所以命令很重要。

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

STDIO流對(duì)于單個(gè)文件的范圍也很容易隱藏,這對(duì)于有競(jìng)爭(zhēng)力的編程非常有用:

#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逐個(gè)聲明并避免using namespace std;因?yàn)樗鼤?huì)產(chǎn)生歧義錯(cuò)誤:

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
                   ^

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


查看完整回答
反對(duì) 回復(fù) 2019-07-08
  • 3 回答
  • 0 關(guān)注
  • 811 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)