Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between getline and std::istream::operator>>()?

Tags:

c++

cin

istream

#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) ;
}
like image 898
user4857442 Avatar asked May 02 '15 16:05

user4857442


People also ask

What is the difference between Getline and CIN in C++?

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.

What is difference between getline () and read () function?

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.

What can I use instead of Getline in C++?

Use the std::ws manipulator in the std::getline . Like: getline(cin >> ws, title); . This will eat potential leading whitespaces, including the newline.


1 Answers

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.

like image 154
Nawaz Avatar answered Oct 05 '22 11:10

Nawaz