利用freopen()函数和fc命令简化程序调试
大家在參加ACM比賽或者參加c/c++實驗技能競賽的時候,如果遇到大量的輸入和大量的輸出時,調試起來很不方便。一來如果結果不正確的話,需要重復輸入大量數據;二來如果大量輸出的話,得仔細檢查輸出結果與正確答案是否一樣。這兩項任務有時讓人很不舒服。
我們可以利用freopen()函數來重定向流,可以使調試起來更加簡單方便。
一個簡單的例子:
#include <iostream> #include <cstdio> using namespace std; int main() { int a; int b; freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while(cin>>a>>b) { cout<<a+b<<endl; } return 0; }在進行輸入與輸出前,將標準輸入流stdin與“in.txt"綁定,標準輸出流與"out.txt"綁定。這樣,只需在工程文件夾下建立in.txt文件,并將輸入寫入其中,就可避免每次都要在控制臺手動輸入了。同理,輸出也將輸出到out.txt里。
在提交代碼時,只需將freopen這兩行代碼注釋掉即可,很方便的。
下面是關于freopen的簡介:
FILE * freopen ( const char * filename, const char * mode, FILE * stream ); Reopen stream with different file or mode Reuses stream to either open the file specified by filename or to change its access mode.If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.If filename is a null pointer, the function attempts to change the mode of the stream. Although a particular library implementation is allowed to restrict the changes permitted, and under which circumstances.The error indicator and eof indicator are automatically cleared (as if clearerr was called).This function is especially useful for redirecting predefined streams like stdin, stdout and stderr to specific files (see the example below). View Code同時,輸出也會輸出到out.txt中,如果輸出量很大的話,比較起來也是很麻煩的。這時,可以將正確結果也存在另一個記事本中(舉例:out1.txt),這樣就可以利用windows下的fc命令將程序的輸出與正確輸出的結果進行比較,也省去一番力氣。
將程序的輸出與正確結果的比較也有更好的方法,比如我使用的windows下的gvim編輯器,就有這個功能,而且比fc命令好用很多。
轉載于:https://www.cnblogs.com/wangaohui/p/3645510.html
總結
以上是生活随笔為你收集整理的利用freopen()函数和fc命令简化程序调试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单实用的Windows命令(一)
- 下一篇: fedora 20 PIL