C + + writes output to file/read data from File

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.