Include the header file first
#include <fstream>
Output to File
Ofstream Fout; declares an output stream object
Fout.open ("output.txt"); Open (if not created) a file
(or directly below with Ofstream Fout ("output.txt"))
Fout.close (); Close File
1Template <classT>2 voidArray<t>:: Showlist () {3Ofstream Fout ("output.txt");4 for(inti =0; i < size; ++i) {5Fout << List[i] <<" ";6cout << List[i] <<" ";7 }8Fout <<Endl;9 fout.close ();Tencout <<Endl; One}
Input from File
Ifstream fin ("input.txt");
1Template <classT>2 voidArray<t>:: Setlist () {3Ifstream Fin ("Input.txt");4 for(inti =0; i < size; ++i) {5 T N;6Fin >>N;7List[i] =N;8 }9}
Attention:
If you want to read a whole line into a char array, we can't use the ">>" operator, because the space (whitespace character) between each word aborts the file's reading.
Want to include the whole sentence, there is a way to read the whole line, it is getline ().
such as: fin.getline (sentence, 100);
C + + writes output to file/read data from File