Reading File Line By Line
Question:21
Write a C++ program to create a file and store text into it further read the contents line by line and display the text.
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> //gets() #include<stdlib.h> //exit() using namespace std; void create() { ofstream abc; char str[80],ch; abc.open("hello"); do { cout<<"Enter the text to store "; fflush(stdin); gets(str); //cin.getline(str,80); abc<<str<<endl; cout<<"Would you like to cont....."; fflush(stdin); cin>>ch; }while(ch=='y' || ch=='Y'); abc.close(); } void display() { ifstream pqr; char str[80]; cout<<"The contents of the file are "<<endl; pqr.open("hello"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1);//return; } while(!pqr.eof()) { pqr.getline(str,80); cout<<str<<endl; } pqr.close(); } int main() { create(); display(); getch(); return(0); }
Question:22
Write a function named “count_lines()” in C++ to read the file named “article.txt”. Count and print total lines starting with ‘a’ or ‘A’.
Sol:
#include<iostream> #include<fstream> #include<conio.h> #include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; void count_lines() { ifstream pqr; char line[80]; int c=0; pqr.open("article.txt"); if (pqr.fail()) { cout<<"Unable to open the file"<<endl; exit(1); } while(!pqr.eof()) { pqr.getline(line,80); if(line[0]=='a' || line[0]=='A') { cout<<line<<endl; c++; } } pqr.close(); cout<<"Total lines "<<c<<endl; } int main() { /* clrscr(); */ count_lines(); return(0); }