We have to write a program that opens a file and asks the user to input string. Then inputting a srarch string we will have to find the inputted string’s position in the opened file.
Solution:
| #include <iostream.h> #include <fstream.h> #include <string.h> #include <conio.h> void main(){ fstream f; f.open("account.cpp",ios::in); cout<<"File opened!!!\n"; cout<<"Enter string: "; char src[80]; char c; cin>>src; int i,j,k,breaker=0; i=j=k=0; int len=strlen(src); int found=0,pos[1000]={0}; while(f){ f.get(c); while ((c==src[i]) && (i<len)){ breaker=1; if (!i) pos[j]=f.tellp(); i++; if (i==len){ found++; j++; breaker=0; break; } f.get(c); } if (breaker) f.seekg(-i, ios::cur); i=0; breaker=0; } cout<<"Total occurance: "<<found; cout<<"\nPosition: "; for (k=0; k<j; k++){ if (k<(j-1)) cout<<pos[k]<<", "; else cout<<pos[k]; } getch(); } |
Discussions:
I had my desired result while I ran the program.
No comments:
Post a Comment