I'm getting started with C++ programming and I have to say that it's one of the few programming languages that I really liked.
Now I am with the subject of data entry by the user, but I have a question, since in some sites I see that they use "cin >> "
and in others they use cin.getline()
.
What is the difference between them?
Which is better?
Within object-oriented programming, it is common for objects to have a series of methods that allow them to interact with the object. It is the example of
cin.getline
.On the other hand, languages like C++ support operator overloading. In some languages like C, each operator fulfills a very specific mission and only for native types (those predefined by the language) and its use cannot be modified under any circumstances. The addition operator serves as an example:
As we have said, in C++ it is possible to redefine the behavior of certain operands to adapt them to particular objects of our program. So we could do the following:
Along the same lines, other operators that can be overloaded are the insert
<<
and remove operators>>
:I'm not going to go into detail about the use of
friend
because that would lead me into a number of topics that are beyond the scope of the question.Of course, overloading operators is something to do only in very special cases to avoid unexpected behavior due to silly language details such as implicit conversions.
As an additional detail, say that the operators can be called just like any other function. So we can do the following:
Thus, the use of the operator
>>
is determined by a series of overloads of the operator, whilecin.getline
it is just a member function ofcin
.Of course, when deciding which option to use, pay close attention to the details of each function. The standard library has few redundant options. This means that two functions can work the same only in appearance.
So, for example,
cin.getline
it reads a text string until a newline (or a null character) is encountered, while the operator>>
stops when it also encounters a space.If, for example, on the keyboard you type
"Esto es una prueba"
:cin.getline
will recover"Esto es una prueba"
cin >> var
will recover"Esto"
This without taking into account the fact that the operator
>>
allows you to retrieve integers, floating point numbers, ... while itcin.getline
only allows you to read text strings.cin
it can "read" (convert, actually cast) any data type and store it in a variable, insteadcin.getline
it only stores strings (expectschar*
as parameter).To show an example of when you would use which: