#include <stdio.h> #include <iostream> using namespace std; int main() { int a,b; freopen("in.txt","r",stdin); //輸入重定向,輸入數據將從in.txt文件中讀取 freopen("out.txt","w",stdout); //輸出重定向,輸出數據將保存在out.txt文件中 while(cin>> a >> b) cout<< a+b <<endl; // 注意使用endl fclose(stdin);//關閉文件 fclose(stdout);//關閉文件 return 0; }
freopen("in.txt","r",stdin)的作用就是把標准輸入流stdin重定向到in.txt文件中,這樣在用scanf或是用cin輸入時便不會從標准輸入流讀取數據,而是從in.txt文件中獲取輸入。
類似的,freopen("out.txt","w",stdout)的作用就是把stdout重定向到out.txt文件中,這樣輸出結果需要打開out.txt文件查看。
函數名:freopen
聲明:FILE *freopen( const char *path, const char *mode, FILE *stream );
所在文件: stdio.h
參數說明:
path: 文件名,用於存儲輸入輸出的自定義文件名。
mode: 文件打開的模式。和fopen中的模式(如r-只讀, w-寫)相同。
stream: 一個文件,通常使用標准流文件。
返回值:成功,則返回一個path所指定文件的指針;失敗,返回NULL。(一般可以不使用它的返回值)
功能:實現重定向,把預定義的標准流文件定向到由path指定的文件中。標准流文件具體是指stdin、stdout和stderr。其中stdin是標准輸入流,默認為鍵盤;stdout是標准輸出流,默認為屏幕;stderr是標准錯誤流,一般把屏幕設為默認。通過調用freopen,就可以修改標准流文件的默認值,實現重定向。