I am going to use a vector, not an array, to do your function. First, an outline of the approach, and couple of other comments:
1. Open the file and, using the getline() method, read the file line by line into a string
2. Use each of these strings to instantiate a stringstream object and read the data from this object into a vector<int> (you can search online how the stringstream class does this or come back here with any further queries)
3. Now you don't need the file any more, so you can close it
4. Run the SequentialSearch() function:
(a) the function offers a menu to try password or quit
(b) it also restricts the maximum number of failed password entry attempts to 4 before it returns, you can change or remove this if you wish
5. Note: I have not done any input validation nor written any code for what would happen if the file did not open - you can/must do this to make your program robust
6. I am using vector instead of array to be able to use of the vector class method push_back() and the STL algorithm find()
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
|
#include<iostream>
#include<fstream>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;
void SequentialSearch(vector<int>&v);
const int max_attempt = 4;
int main(){
ifstream File;
int num, input, attempt = 0;
vector<int>v;
File.open("F:\\test.txt");
if(File.is_open()){
string line;
while(getline(File, line)){
stringstream stream(line);
while(stream>>num){
v.push_back(num);
}//closes inner while loop;
} // closes outer while loop;
} // closes if statement;
File.close();
SequentialSearch(v);
}
void SequentialSearch(vector<int>&v){
bool fQuit = false;
int attempt = 0;
while(!fQuit){
cout<<"1. Try password \n2. Quit\n";
int choice;
cin>>choice;
switch(choice){
case 1:{//case statments have to be within braces to scope local variables declared;
while(attempt < max_attempt){
cout<<"Enter key: (attempts remaining "<<(max_attempt - attempt)<<"): \n";
int key;
cin>>key;
if(find(v.begin(), v.end(), key)!=v.end()){
cout<<"Success\n";
fQuit = true;
break;//breaks out of the inner while loop;
}
else{
attempt++;
cout<<"Fail\n";
}
}
if(attempt == max_attempt){
cout<<"Max attempt reached\n";
fQuit = true;
}
}//closes case 1;
break;
case 2:
fQuit = true;
cout<<"Goodbye\n";
break;
default:
cout<<"Wrong entry, try again \n";
break;
}//closes switch statement;
}//closes while loop;
}// closes function definition;
|