ACM中freopen的使用

百度百科上的定义:

freopen是被包含于C标准库头文件中的一个函数,用于重定向输入输出流。该函数可以在不改变代码原貌的情况下改变输入输出环境,但使用时应当保证流是可靠的。

用途一:

输入重定向。当调试代码时,可以将测试数据存在 in.txt 文件中,用freopen读取

测试:

写出下面的代码

#include 
#include 
using namespace std;

int main(void)
{
	int a, b;
	// 输入重定向,读取 in.txt 中的数据 
	freopen("in.txt", "r", stdin);
	
	cin >> a >> b;
	cout << a + b << endl;
	
	// 关闭输入流 
	fclose(stdin);
	
	return 0;
}

在当前代码的目录下创建一个 in.txt,里面的内容为

1 2

运行代码,运行结果为

3

用途二:

输出重定向。将输出数据保存在 out.txt 文件中

测试:

写出如下的代码

#include 
#include 
using namespace std;

int main(void)
{
	int a, b;
	// 输入重定向,读取 in.txt 中的数据 
	freopen("in.txt", "r", stdin);
	// 输出重定向,将答案写入 out.txt 中 
	freopen("out.txt", "w", stdout);
	
	cin >> a >> b;
	cout << a + b << endl;
	
	// 关闭输入流 
	fclose(stdin);
	// 关闭输出流 
	fclose(stdout);
	
	return 0;
}

在当前代码的目录下创建一个 in.txt,里面的内容为

1 2

运行程序,发现当前目录出现了一个 out.txt,里面的内容为

3

用途三:

多组输入

测试:

#include 
#include 
using namespace std;

int main(void)
{
	int a, b;
	// 输入重定向,读取 in.txt 中的数据 
	freopen("in.txt", "r", stdin);
	
	while (cin >> a >> b) {
		cout << a + b << endl;
	}
	
	// 关闭输入流 
	fclose(stdin);
	
	return 0;
}

在当前代码的目录下创建一个 in.txt,里面的内容为

1 1
2 2
3 3
4 4

运行代码,运行结果为

2
4
6
8

你可能感兴趣的:(#,模板合集,#,杂记,#,程序设计基础:C语言)