利用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