#include <iostream>
#include <string>
using namespace std;
int main()
{
string username;
cout<< "username" ;
cin >> username;
}
So I was curious on what's the difference between these two codes, I heard it's the same thing but if it is then why two ways of doing it then?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string username;
cout << "username" ;
getline (cin,username) ;
}
The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input. That's where the getline() function comes in handy.
getline by comparison will pull the delimiter off the stream, but then drop it. It won't be added to the buffer it fills. get looks for \n , and when a specific number of characters is provided in an argument (say, count ) it will read up to count - 1 characters before stopping. read will pull in all count of them.
Use the std::ws manipulator in the std::getline . Like: getline(cin >> ws, title); . This will eat potential leading whitespaces, including the newline.
The difference is thatstd::getline
— as the name suggests — reads a line from the given input stream (which could be, well, std::cin
) and operator>>
reads a word1.
That is, std::getline
reads till a newline is found and operator>>
reads till a space (as defined by std::isspace
) and is found. Both remove their respective delimiter from the stream but don't put it in the output buffer.
1. Note that >>
can also read numbers — int
, short
, float
, char
, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With