Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++를 사용하여 텍스트 파일에서 데이터 읽기

<시간/>

텍스트 파일에서 데이터를 읽어오는 C++ 프로그램입니다.

입력

tpoint.txt is having initial content as
“Tutorials point.”

출력

Tutorials point.

알고리즘

Begin
   Create an object newfile against the class fstream.
   Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.
   If file is open then
      Input a string “Tutorials point" in the tpoint.txt file.
      Close the file object newfile using close() method.
   Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.
   If file is open then
      Declare a string “tp”.
      Read all data of file object newfile using getline() method and put it into the string tp.
      Print the data of string tp.
   Close the file object newfile using close() method.
End.

예시

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("tpoint.txt",ios::out);  // open a file to perform write operation using file object
   if(newfile.is_open())     //checking whether the file is open
   {
      newfile<<"Tutorials point \n"; //inserting text
      newfile.close(); //close the file object
   }
   newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object
   if (newfile.is_open()){   //checking whether the file is open
      string tp;
      while(getline(newfile, tp)){  //read data from file object and put it into string.
         cout << tp << "\n";   //print the data of the string
      }
      newfile.close();   //close the file object.
   }
}

출력

Tutorials point