
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Read Data from a Text File using C++
This is a C++ program to read data from a text file.
Input
tpoint.txt is having initial content as “Tutorials point.”
Output
Tutorials point.
Algorithm
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.
Example
#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. } }
Output
Tutorials point
- Related Articles
- How to read data from a file using FileInputStream?
- How to read data from *.CSV file using JavaScript?
- How to read an entire line from a text file using Python?
- Read and write a string from a text file
- How to read a number of characters from a text file using Python?
- Read integers from a text file with C++ ifstream
- How to read data in from a file to String using java?
- How to read a text file from resources in Kotlin?
- How to read the data from a file in Java?
- How to read data from .csv file in Java?
- How to read a text file with C++?
- How to read a text file in Python?
- Write a C program to read a data from file and display
- How to read complete text file line by line using Python?
- How to read a simple text file in an Android App using Kotlin?

Advertisements