Site icon DataFlair

How to Read Data from File Line by Line in C++

Free C++ course with real-time projects Start Now!!

Program 1

#include<iostream>
#include<string>
#include<fstream>
#define clrscr() system("cls");
using namespace std;
int main()
{
    // open file in read mode
    fstream fin;
    clrscr();
    fin.open("g://cppdata/student.txt",ios::in);
    if(fin.is_open()) // check file open
    {
          string st;
          int i=0;
          while(getline(fin,st)) // till file is not reach to end 
          {
              cout<<st<<"\n";  
              i++;
          } 
         cout<<"\n Total lines :"<<i; 
    }
    else
    cout<<"\nfile error";
    return 0;
}

 

Exit mobile version