Problem with getline

Here is my code. The second time that i use getline, it doesn't work. The variable is not given the value that the user inputs. But the first time i use it, it's ok.

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
#include <iostream>
#include <string>
using namespace std;

void main()
{
	// define variables to store username and passwrod
	string username;
	string pass;

	// ask user to input username
	cout << "Please enter your username : ";
	getline (cin, username);

	// ask user to input password
	/** I think the problem is here.
	    the pass variable is not given the value input 
		by the user **/

	cout << "Please enter a password : " ;
	getline (cin, pass);


	// lfc is a valid password to stevie g
	if ((pass == "lfc") && (username == "stevie g"))
	{
		cout << "Access Granted" << endl;
		cout << "Welcome MR : " << username << endl;
		cout << "Password entered was : " << pass << endl;
	}
	else
	{
		cout << "Password/username combination incorrect" << endl;
		cout << "You entered the following log in :" << endl;
		cout << endl;

		/** The username is ok; it appears as the user has input **/
		cout << "Username : " << username << endl;

		/** the pass variable seems to contain no value
		    when seen in the console window **/
		cout << "Password : " << pass << endl << endl;
	}

	return;
}
Works fine for me. GCC 3.4.5

FYI: It's int main(), not void main(). void main is not supported by alot of compilers, and it's not standard C++.
Yeah, change your main and see how it runs for you?
I tried changing void main() to int main(), but the same problem persists. doesn't work for me !!

Any other suggestions??

My guess would be: change 'passwrod' in line 1 in 'password'
I used string pass to hold the password.
I can't see passwrod...i didn't understand what you meant...
is it seeming to skip to the end of the program then? If so then the buffer for cingetline needs to be cleared before it is used again. this can be done with cin.ignore();
Last edited on
It works, thnx :)
Now i got another question :P
How can i avoid pressing enter twice when using getline to input a line?
can you be more specific as to what your problem is and post some of the code for the lines you are experiencing difficulty
when i use cin >> pass for example, the user enters the password at the console and on pressing enter the value that has been typed in gets assigned to pass.
Now if i use getline (cin, pass) the user has to press 'enter' on the keyboard twice after having entered a password at the console.

How can i get the input of the line with the user pressing enter only once??
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string a;
    getline (cin,a);
    cout<<a;
    cin.ignore();
    return 0;
}


I dont see what you main...
Topic archived. No new replies allowed.