Returning Strings?

Hi,

Writing a very basic function that checks a password is correct, no checks for username of anything. Program works I just cant get the return message "Access granted!" printed..?

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

using namespace std;

string check_pass(string username, string password);

int main(){
	string username;
	string password;
	
	cout<<"Please enter your username: ";
	cin>>username;
	cout<<"Please enter your password: ";
	cin>>password;
	check_pass(username, password);
}

string check_pass(string username, string password){
	for (int i=3; i>=0; i--){
		if (password!="Programming"){
			cout<<"Incorrect, access denied. "<<i<<" chances left"<<endl<<endl;
			cout<<"Please enter your username: ";
			cin>>username;
			cout<<"Please enter your password: ";
			cin>>password;
		}
		if (password=="Programming"){
			return "Access granted!";
		}
		if (i==1){
			cout<<"Too many incorrect login attemps.";
			exit(0);
		}
	}
	return "Access granted!";
}


Thanks for any help
Add a cout << before check_pass, like so:

cout << check_pass(username, password);
Thanks man, that actually does make so much sense I cant believe how stupid I am..
Although, OP, keep in mind that that might not be the best approach to your problem. When creating functions that gives error feedback you should use bools or ints.
Consider the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool check_pass(string username, string password)
{
    //some logic
    if(pass) return true;
    return false;
}

int main()
{
    if(check_pass(username, password))
        cout << "Access granted!" << endl;
    else
        cout << "Access denied!" << endl;
}


That is a much more intuitive approach because you would be able to do other things with the results from check_pass. Perhaps you don't just want to output the results as a string, but you want to check the result to see if it's a pass and then activate some other procedure. If you return a string "Access granted!" from the check function, you would have to do this to check if the username/pass worked
1
2
3
4
5
6
7
int main()
{
    if(check_pass(username, password) == "Access granted!")
        //do something
    else
        //do something else.
}


It creates a lot more for you to write if, say, you had to use check_pass a lot more times in your code.
Ok, Thanks Thumper I can see what you are saying. So change the function to a bool, change the return messages to either true or false and add a if statement in main? Ill try this now and let ya know how I go sounds pretty straight forward.
Cheers Thumper, works perfectly and looks much better, what you said makes perfect sense. Thanks for your help :)
Cheers, glad I could help. :)
Topic archived. No new replies allowed.