C、C++ 標准輸入重定向 & 萬能頭 - 編程技巧


轉眼到了畢業季,大家都在忙着找暑期實習;我也投了一個,是阿里巴巴的暑期實習;實習,少不了機試,又想起了大一時曾經湊過acm的熱鬧;當時學到一個技巧,是使用重定向向輸入輸出函數,這樣在進行測試的時候就比較方便了;

這樣調試的時候,不用從控制台進行手動輸入,直接從文件中進行輸入就行;這樣也方便debug;

引入頭文件:

#include <cstdio>

經典使用樣例:(我一般只重定向輸入,還是在標准輸出中輸出)

freopen("in.txt","r",stdin);  
freopen("out.txt","w",stdout); 

函數解釋:(可以使用 man freopen 進行查詢)

#include <stdio.h>
FILE *
freopen(const char *path, const char *mode, FILE *stream);
The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream
with it.  The original stream (if it exists) is closed.  The mode argument is used just as in the fopen() function.
If the path argument is NULL, freopen() attempts to re-open the file associated with stream with a new mode.  The new mode must be
compatible with the mode that the stream was originally opened with: Streams open for reading can only be re-opened for reading,
streams open for writing can only be re-opened for writing, and streams open for reading and writing can be re-opened in any mode.
The ``x'' mode option is not meaningful in this context.
The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout).

另外一個技巧就是,c++的萬能頭:

#include<bits/stdc++.h> 

部分平台,不支持此頭文件;經過我的測試,macos 的clang++ 11.0.0 好像不支持這個文件;但是g++ 9.3.0通過我的測試,好像支持這個文件;

2021年3月9日 16點19分:

常用編譯命令參考:使用 c++ 11 標准;

c++ -std=c++11 example.cc -o example ; ./example

參考代碼:

#include <cstdio>
#include <iostream>

int main(){
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout); // 使用w模式,每次打開文件都清空內容;
    std::string buffer;
    while (std::cin >> buffer)
    {
        std::cout << buffer << " ";
    }
    std::cout << std::endl;
    return 0;
}

保持更新,轉載請注明出處;更多內容請關注cnblogs.com/xuyaowen; 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM