C++ 读取文件及保留小数方法
做图论作业时,需要从文件中读取整型数据。之前都是在标准输入输出流中读取和输出。今小记一下。
读取文件
使用文件流ifstream
最简洁的方法是使用文件流:
ifstream infile(filename)
假设 test.txt 文件中存放5 6:
	ifstream infile("test.txt");
	int n, m;
	infile >> n >> m;
这样就可以实现读取文件中的内容了。
如果想读取至文件尾,则使用eof()方法:
	vector<int> tmp;
	while (!infile.eof()) {
		int n; 
		infile >> n;
		tmp.push_back(n);
	}
不过以下教程不推荐使用eof方法,因为它可能导致一次额外的迭代。不过我认为eof方法比较简单和通用,这个见仁见智。
如何用 C++ 从文件中读取整数
读取整行可以用getline(),以字符串形式存储:
	ifstream infile("tt.txt");
	string line;
	while (getline(infile, line)) {
		cout << line <<endl;
	}
保留小数
使用fixed结合setprecision(n)
头文件是 #include <iomanip> 
setprecision(n) 控制保留n位有效数字
写一次,对之后的数字都有效:
	double t = 1.414;
	cout << fixed << setprecision(2);
	cout << t <<endl; //输出1.41 
	double pi = 3.14159;
	cout << pi << endl; //输出3.14
