1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
// This program search for a sequence wrote before in a sequence already written in a file.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm> // search(...);
#define N 300
using namespace std;
//PROTOTYPE
void OpenFile(string path, int sequencefile[N], int &i);
void CountSequence(int sequencefile[N], int i);
int main()
{
int i=0;
int sequencefile[N];
string path;
cout<<"Write the path of the file: ";
cin>>path;
OpenFile(path, sequencefile, i);
CountSequence(sequencefile, i);
return 0;
}
//Open the file and load the sequence.
void OpenFile(string path, int sequencefile[N], int &i) //"int i" must return his vaule for the next function.
{
ifstream file(path.c_str()); //".c_str()" Get C string equivalent.
if(file.is_open()) //It's true if the file is open (.is_open()).
{
while(file>>sequencefile[i]) //Load every number of the sequence into an array of integer.
{
i++; //Next position in the array.
}
}
else
{
cout<<"\nError! File not found!"<<endl;
exit(1);
}
}
//This function count how many times the sequence written has been found.
void CountSequence(int sequencefile[N], int i)
{
int sequence[N];
int *result; //"result" must be a pointer in order to save the result from "search()"
int max=0, countsequence=0;
cout<<"Write the sequence of numbers you want to search(greater than 1): ";
cin>>max;
while(max<=1)
{
cout<<"You wrote an invalid number. Retry."<<endl;
cin>>max;
}
cout<<"Write "<<max<<" numbers."<<endl;
for(int j=0;j<max;j++)
{
cin>>sequence[j]; //Load every number of the sequence into another array of integer.
}
do
{
result=search(sequencefile,sequencefile+i,sequence,sequence+max);
//Searches the range [sequencefile,sequencefile+i) for the first occurrence of the sequence defined by [sequence,sequence+max),
//and returns an iterator to its first element, or sequencefile+i if no occurrences are found.
if(result!=sequencefile+i)
{
++countsequence;
++result;
}
}while(result==sequencefile+i);
cout<<"The sequence has been found "<<countsequence<<" times"<<endl;
}
|