C++ 把输出结果写入文件/从文件中读取数据

先包含头文文件

#include<fstream>


输出到文件

ofstream fout;  //声明一个输出流对象

fout.open("output.txt");  //打开(如过没有则创建)一个文件

(或者直接如下用ofstream fout("output.txt"))

fout.close();  //关闭文件

 1 template <class T>
 2 void Array<T>::showlist() {
 3     ofstream fout("output.txt");
 4     for (int i = 0; i < size; ++i) {
 5         fout << list[i] << " ";
 6         cout << list[i] << " ";
 7     }
 8     fout << endl;
 9     fout.close();
10     cout << endl;
11 }

从文件输入

ifstream fin("input.txt");

1 template <class T>
2 void Array<T>::setlist() {
3     ifstream fin("input.txt");
4     for (int i = 0; i < size; ++i) {
5         T n;
6         fin >> n;
7         list[i] = n;
8     }
9 }

注意:

如果想把整行读入一个char数组, 我们没办法用">>"操作符,因为每个单词之间的空格(空白字符)会中止文件的读取。
想包含整个句子, 有读取整行的方法, 它就是getline()。
如:fin.getline(sentence, 100);

原文地址:https://www.cnblogs.com/heiqiaoshusheng/p/4675024.html