This program demonstrates file operations in c++. The program reads as input five names and stores it in a file named sample.txt using the out statement, then the file is closed. Next the program reads a new name to be searched in the file and stores it in the variable name. Then the program program compares each name in the file with the value stored in the variable name, if there is a match the string is found in the file. Otherwise the string is not present in the file.
Program
//c++ program to check whether a particular word is present in the file #include<iostream.h> #include<conio.h> #include<fstream.h> #include<string.h> #include<process.h> void main() { int i; char name[20],t[20]; ofstream out; out.open("sample1.txt"); cout<<"Enter five names\n\n"; for(i=0;i<5;i++) { cin>>name; out<<name<<"\n"; } out.close(); cout<<"Enter the name to be searched for"; cin>>name; ifstream in; in.open("sample1.txt"); while(in) { in.seekg(2,ios::beg); in>>t; cout<<"\n"<<t; } in.close(); in.open("sample1.txt"); while(in) { in>>t; if(strcmp(name,t)==0) { cout<<"\nString found!!!"; getch(); in.close(); exit(0); } } cout<<"\nString not found!!!"; in.close(); getch(); }
No comments:
Post a Comment