PAT要注意的地方
阿新 • • 發佈:2019-02-17
freopen("debug\\in.txt","r",stdin)的作用就是把標準輸入流stdin重定向到debug\\in.txt檔案中,這樣在用scanf或是用cin輸入時便不會從標準輸入流讀取資料,而是從in.txt檔案中獲取輸入。只要把輸入資料事先貼上到in.txt,除錯時就方便多了。//C語法: #include <stdio.h> int main() { int a,b; freopen("debug\\in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取 freopen("debug\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中 while(scanf("%d %d",&a,&b)!=EOF) printf("%d\n",a+b); fclose(stdin);//關閉檔案 fclose(stdout);//關閉檔案 return 0; } //C++語法 #include <stdio.h> #include <iostream.h> int main() { int a,b; freopen("debug\\in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取 freopen("debug\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中 while(cin>>a>>b) cout<<a+b<<endl; // 注意使用endl fclose(stdin);//關閉檔案 fclose(stdout);//關閉檔案 return 0; }
類似的,freopen("debug\\out.txt","w",stdout)的作用就是把stdout重定向到debug\\out.txt檔案中,這樣輸出結果需要開啟out.txt檔案檢視。
需要說明的是:
1. 在freopen("debug\\in.txt","r",stdin)中,將輸入檔案in.txt放在資料夾debug中,資料夾debug是在VC中建立工程檔案時自動生成的除錯資料夾。如果改成freopen("in.txt","r",stdin),則in.txt檔案將放在所建立的工程資料夾下。in.txt檔案也可以放在其他的資料夾下,所在路徑寫正確即可。
2. 可以不使用輸出重定向,仍然在控制檯檢視輸出。
3. 程式除錯成功後,提交到oj時不要忘記把與重定向有關的語句刪除。