Getline

Hello

This is a question I am so stuck on and just don't get. I'm sorry if this sounds stupid but what is "getline" used for? I'm having a lot of trouble trying to understand its usage. For example in the code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string password;

cout << "Enter your password: " << "\n";
getline( cin, password, '\n' );
if (password == "test")
{
cout << "Access allowed" << "\n";
}
else
{
cout << "Bad password. Denied Access!" << "\n";

return 0;
}

}

What is the "getline( cin, password, '\n' );" used for?

Cant I just use "cin >> password;"?

What's the difference?

Thanks!
Generally, you would use getline when you want to extract an entire line of text until you reach a new line(The new line been \n). For example, let's say you have a string called myName and lets say that your name is Bob Roberts. If you do cin >> myName and type Bob Roberts, the computer is only going to extract the string Bob and discard the string Roberts. If you want to extract the entire name, you should use getline. Also be aware that a certain problem can occur if you mix cin and getline together in a program.
Last edited on
Oh okay that makes sense.

Thank you.
Topic archived. No new replies allowed.