What is 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 to know what is the difference between the two codes, I heard that it is the same thing, but if so, then two ways to do it?

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

int main()
{  
   string username;
   cout << "username" ;
   getline (cin,username) ;
}
+4
source share
5 answers

The difference is that std::getline- as the name implies: - reads a line from a given input stream (which may be, well, std::cin) and operator>>reads word 1 .

That is, it std::getlinereads until a newline is found, and operator>>reads to a space (as defined std::isspace) and is found. Both remove their respective delimiter from the stream, but do not put it in the output buffer.

1. , >>int, short, float, char ..

+8

>> std::istream .

getline ('\n' ).

, getline , , →

+6

getline: stream . getline a char * , . a std::string, . , ('\n').

operator>> . , int i; std::cin >> i;, , getline . . , .

+3

cin, , getline() cin>>, , getline() . , :

cin>>consoleInputVariable;
cin.ignore();
getline(cin,getLineVariable);

, . ignore(), .

0

: getline: , , "\n". . , :

string someStr;
getline(cin, someStr);  //here if you enter 55, it will be considered as someStr="55";

" → " ( ): . , , char. .

int someInt;
std::cin >> someInt;  //here if you enter "55some", >> will only consider someInt=55;

, :

string someStr;
cin >> someStr;   

, " ", cin , "" - , "( ), I, someStr =" I".

IMP: → getline , . → , "\n" (newline char) . , ,

int someStr, someStr2;
std::cin >> someStr;   //here you enter "Batman"
getline(cin, someStr2);  //here you enter "Bruce"

since → does not recognize the "\ n" char, it will only see "Batman" and exit the buffer, leaving "\ n" for someStr2. So, someStr2 will not get "Bruce", but "" (new char line).

0
source

All Articles