Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

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

#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) ;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...