Help with functions/files

Pages: 12
So I have done the code without the function, which is where I am completely stuck. If you could please help me that would be awesome!

So the program searches a data file for a number that the user enters. It either says access granted or not matching. The data file contains 300 numbers. I will post 10 so I don't take up too much room. I am pretty confused on how to do the function in general.

Directions for function: The input parameters for the SequentialSearch() function are:
• 1-D array which has all the data,
• Search Key,
• Size of the array.

Data file:
1488
1490
1492
1494
1496
1498
1500
1502
1504
1506

Code without function:
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
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
	int input[300];
	int i(0), key(0), flag(0);

	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n";
	cout << "ENTER 4 DIGIT CODE: ";
	cin >> key;
	ifstream textfile("SystemAccessCodes.txt");
	while (!textfile.eof()) {
		textfile >> input[i];
		for (int i = 0; i < input[i]; i++) {
			if (input[i] == key) {
				flag = 1;
				break;
			}
		}
	}
	if (flag == 1) {
		cout << "===================================\n";
		cout << "\tACCESS GRANTED\n\t   WELCOME\n";
		cout << "===================================\n";
	}
	else {

		cout << "===================================\n";
		cout << "     Not Matching. Try Again" << endl;
		cout << "===================================\n";
	}

	system("pause");
	return 0;
}

Last edited on
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post, highlight your code and click the <> button on the right.

while (!textfile.eof())
Prefer this:
while( textfile >> input[i] )

1
2
3
4
5
6
for (int i = 0; i < input[i]; i++) {
        if (input[i] == key) {
        flag = 1;
        break;
    }
}

You don't need to loop through the whole array. Just compare the current value with the key.
Last edited on
One of my problems too but thank you. This helps me alot.
Thank you for your response @ integralfx

Sorry about that, I fixed the code tags and also the while loop. That makes sense not to loop through the whole array, I thought that was how it worked. Any ideas on the function part?
Last edited on
Any ideas on the function part?
1
2
3
4
5
6
7
8
9
10
11
// returns the index if val is found in arr, otherwise returns -1
int SequentialSearch( const int arr[], const int val, const int size = 300 )
{
    /*
    Loop through arr
    Compare current element with val
        If they're equal stop the loop and return the index

    If element isn't found return some impossible value like -1
    */
}
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;  
Last edited on
@integralfx Thanks, but I am still completely lost on the function. I'm not quite sure what should be my parameters, what should be in the body of the function and what the return value should be.

Directions for function: The input parameters for the SequentialSearch() function are:
• 1-D array which has all the data,
• Search Key,
• Size of the array.

@gunnerfunner Thanks but I have not gotten to vectors. So I am trying to do it the way I am being asked to do it. With a Function.


The code is not working properly because of the function. Please help.

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
#include<iostream>
#include<fstream>

using namespace std;

int SequentialSearch(int a[], int size, int key, int flag)
{
	cin >> key;
	ifstream textfile("SystemAccessCodes.txt");
	while (textfile >> a[size]) {
		for (int i = 0; i < size; i++) {
			if (a[size] == key) {
				flag = 1;
				break;
			}
		}
	}
	return(flag);
}

int main()
{
	int input[300];
	int size = 300;
	int i(0), key(0), flag(0);

	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n";
	cout << "ENTER 4 DIGIT CODE: ";
	SequentialSearch(input, size, key, flag);
	
	if (flag == 1) {
		cout << "===================================\n";
		cout << "\tACCESS GRANTED\n\t   WELCOME\n";
		cout << "===================================\n";
	}
	else {

		cout << "===================================\n";
		cout << "     Not Matching. Try Again" << endl;
		cout << "===================================\n";
	}

	system("pause");
	return 0;
}
Last edited on
Ok, here's the function on the lines of how you'd like it but I'd still recommend you start using vectors, algorithms (i.e the STL in general) as soon as you can:

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

#include<iostream>
#include<fstream>

using namespace std;

bool SequentialSearch(int num_arr[], int size, int key, bool match);

int main(){
    ifstream File;
    int num_arr[10];
    int i = 0;
    File.open("F:\\test.txt");
    if(File.is_open()){
        while(File >> num_arr[i]){
                i++;
              } //closes while loop;
            }//closes if statement;
     File.close();

    cout<<SequentialSearch(num_arr, 10, 1500, false)<<"\n";// can write 0 instead of false for the bool as well;
}
bool SequentialSearch(int num_arr[], int size, int key, bool match){
	int position = 0;

    while (position < size && match == false){
        if (num_arr[position] == key){
            match = true;
        }
        else{
            position++;
		}
    }
    return match;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int SequentialSearch(int a[], int size, int key, int flag)
{
	cin >> key;
	ifstream textfile("SystemAccessCodes.txt");
	while (textfile >> a[size]) {
		for (int i = 0; i < size; i++) {
			if (a[size] == key) {
				flag = 1;
				break;
			}
		}
	}
	return(flag);
}

I would recommend you read the data into the array in main(), and pass it to SequentialSearch(),


I'm not quite sure what should be my parameters, what should be in the body of the function and what the return value should be.


Parameters:

Directions for function: The input parameters for the SequentialSearch() function are:
• 1-D array which has all the data,
• Search Key,
• Size of the array.


Function body:
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
int SequentialSearch( const int arr[], const int val, const int size = 300 )
{
    // Loop through arr
    for( int i{}; i < size; i++ ) {
    	if( arr[i] == val ) {
    	    /*
	    We have a match!

	    Return the index so it can be used to
	    access the element in the array
    	    */
    	    return i;
    	}
    	/*
	There is no need for an else statement, as
	we want to keep iterating through the array
	until a match is found.
		
	We don't want to stop the loop, as haven't iterated
	through all the elements in the array yet, so an else
	statement is unnecessary.
    	*/
    }

    /*
    Now that the program has reached this point,
    we can safely assume that the element wasn't found,
    as if it was we wouldn't be here, due to the return i
    statement.

    Thus, we can return some impossible value like -1, as
    the index of any array must be greater than or equal to 0.
    
    In main(), you can check if the element wasn't found by checking if
    the return value is -1.
    */
    return -1;	
}

Last edited on
@integralfx thank you for explaining that. Makes a lot of sense. But I am still having a little trouble and im not sure where. I dont know if its not reading the data file now or when I went to call the function I placed it into the wrong area. Like I said earlier I do have the program running correctly without the function I am just having a lot of trouble trying to incorporate the function.

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
#include<iostream>
#include<fstream>

using namespace std;
int SequentialSearch(const int arr[], const int key, const int size = 300)
{
	
	for (int i = 0; i < size; i++) {
		if (arr[i] == key) {
			int flag = 1;
			return i;
		}
	
	}

	
	return -1;
}

int main()
{
	int input[300];
	int i, key(0), flag(0), size = 300;
	int maxtry = 3;

	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n\n";
	for (int x = 1; x <= maxtry; x++) {
		cout << "Attempt " << x << "/" << maxtry << ": ";
		cout << "ENTER 4 DIGIT CODE: ";
		cin >> key;
		ifstream textfile("SystemAccessCodes.txt");
		while (!textfile.eof()) {
			textfile >> input[i];

			
		}
		SequentialSearch(input, size, key);
		if (flag == 1) {
			cout << "===================================\n";
			cout << "\tACCESS GRANTED\n\t   WELCOME\n";
			cout << "===================================\n";
			break;
		}
		else {
			if (x == maxtry && flag != 1)
			{
				cout << "===================================\n";
				cout << "\tACCESS DENIED\n\t     BYE\n";
				cout << "===================================\n";
				break;
			}
			cout << "     NOT MATCHING! TRY AGAIN\n" << endl;
		}
	}



	system("pause");
	return 0;
}
Last edited on
Hello w0rd,

The problem I see is in line 37 SequentialSearch(input, size, key); will return a value, but you have nothing to receive it in. What you need is flag = SequentialSearch(input, size, key);. Otherwise flag will always equal zero.

Hope that helps,

Andy
Handy Andy,

Thank you for your reply so I updated the code. It still says not matching when I am entering a number that is in the data file.

Updated code
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
#include<iostream>
#include<fstream>

using namespace std;
int SequentialSearch(const int arr[], const int key, const int size = 300)
{

	for (int i = 0; i < size; i++) {
		if (arr[i] == key) {
			int flag = 1;
			return flag;
		}

	}


	return -1;
}

int main()
{
	int input[300];
	int i, key(0), flag(0), size = 300;
	int maxtry = 3;

	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n\n";
	for (int x = 1; x <= maxtry; x++) {
		cout << "Attempt " << x << "/" << maxtry << ": ";
		cout << "ENTER 4 DIGIT CODE: ";
		cin >> key;
		ifstream textfile("SystemAccessCodes.txt");
		while (!textfile.eof()) {
			textfile >> input[i];


		}
		SequentialSearch(input, size, key);
		flag = SequentialSearch(input, size, key);
		if (flag == 1) {
			cout << "===================================\n";
			cout << "\tACCESS GRANTED\n\t   WELCOME\n";
			cout << "===================================\n";
			break;
		}
		else {
			if (x == maxtry && flag != 1)
			{
				cout << "===================================\n";
				cout << "\tACCESS DENIED\n\t     BYE\n";
				cout << "===================================\n";
				break;
			}
			cout << "     NOT MATCHING! TRY AGAIN\n" << endl;
		}
	}



	system("pause");
	return 0;
}
Aren't size and key different ways round in your function definition and function call?

Also, why call SequentialSearch twice?
Lastchance,

Thank you for your reply. I fixed that. But It seems if I enter any number that is in the file it returns not matching try again. But if I enter the very last number in the file it works and says access granted.
Well, your input is wrong. i hasn't been defined when you use it in line 33:
textfile >> input[i]

Also, this input routine should precede the for loop. You appear to be re-reading this file every try (and you never close it).
Last edited on
Isn't it defined in line 31?

Also when I put it outside the for loop, and when any number in the file it returns not matching.
Last edited on
???
I'm looking at the code you supplied at 8.47pm today and line 31 starts
ifstream textfile ...
It certainly doesn't set i. Have you edited this code? Are we looking at the same version?
@ lastchance Sorry Im just probably confusing myself. Line 23 has int i, and line 31- 33 has
ifstream textfile("SystemAccessCodes.txt");
while (!textfile.eof()) {
textfile >> input[i];

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
#include<iostream>
#include<fstream>

using namespace std;
int SequentialSearch(const int arr[], const int key, const int size = 300)
{

	for (int i = 0; i < size; i++) {
		if (arr[i] == key) {
			int flag = 1;
			return flag;
		}

	}


	return -1;
}

int main()
{
	int input[300];
	int i, key(0), flag(0), size = 300;
	int maxtry = 3;

	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n\n";
	for (int x = 1; x <= maxtry; x++) {
		cout << "Attempt " << x << "/" << maxtry << ": ";
		cout << "ENTER 4 DIGIT CODE: ";
		cin >> key;
		ifstream textfile("SystemAccessCodes.txt");
		while (!textfile.eof()) {
			textfile >> input[i];


		}
		SequentialSearch(input, size, key);
		flag = SequentialSearch(input, size, key);
		if (flag == 1) {
			cout << "===================================\n";
			cout << "\tACCESS GRANTED\n\t   WELCOME\n";
			cout << "===================================\n";
			break;
		}
		else {
			if (x == maxtry && flag != 1)
			{
				cout << "===================================\n";
				cout << "\tACCESS DENIED\n\t     BYE\n";
				cout << "===================================\n";
				break;
			}
			cout << "     NOT MATCHING! TRY AGAIN\n" << endl;
		}
	}



	system("pause");
	return 0;
}
Hello w0rd,

Lines 31 - 36 need to be above the for loop and once you have finished loading the array you need to close the file.

Line 5 in the function definition you are receiving an array, key, size, yet in line 38 you are sending array, size, key. Wrong order it makes key in the function equal to 300 and size equal to whatever you are trying to find.

Try changing that and see if that works.

Hope that helps,

Andy

P.S. on line 5 the = 300 is not needed. Consider what would happen if size became less than 300.
Last edited on
Hello Andy,

Thank you again for the reply. I made the changes and it still only says access granted for the last number in the file.

Updated code:
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
#include<iostream>
#include<fstream>

using namespace std;
int SequentialSearch(const int arr[], const int key, const int size = 300)
{

	for (int i = 0; i < size; i++) {
		if (arr[i] == key) {
			int flag = 1;
			return flag;
		}

	}


	return -1;
}

int main()
{
	int input[300];
	int i, key(0), flag(0), size = 300;
	int maxtry = 3;

	ifstream textfile("SystemAccessCodes.txt");
	while (!textfile.eof()) {
		textfile >> input[i];
	}
	textfile.close();
	cout << "==== ENTER YOUR CODE TO ACCESS INTO THE SYSTEM ====\n\n";
	for (int x = 1; x <= maxtry; x++) {
		cout << "Attempt " << x << "/" << maxtry << ": ";
		cout << "ENTER 4 DIGIT CODE: ";
		cin >> key;

		SequentialSearch(input, key, size);
		flag = SequentialSearch(input, key, size);
		if (flag == 1) {
			cout << "===================================\n";
			cout << "\tACCESS GRANTED\n\t   WELCOME\n";
			cout << "===================================\n";
			break;
		}
		else {
			if (x == maxtry && flag != 1)
			{
				cout << "===================================\n";
				cout << "\tACCESS DENIED\n\t     BYE\n";
				cout << "===================================\n";
				break;
			}
			cout << "     NOT MATCHING! TRY AGAIN\n" << endl;
		}
	}



	system("pause");
	return 0;
}
Pages: 12