Doubt regarding syntax

in some cases we are using cin.getline and in others we are using getline( cin, a[i] ) etc. where and how do we need to use it?

Hello @ashishxmathew ,

  1. cin
    It is used to read a word or character.
    It terminates on encountering whitespace or endline charater (’\n’)
  2. cin.get(char_array,number_of_characters,delimiter)
    To read characters including special characters like ’ ', β€˜\n’ and β€˜\t’.
  3. cin.getline(char_array,max_Size,delimiter)
    It is used to read a sentence or a paragraph.
    It terminates on encountering endline character.
    It also reads the whitespace.

Difference?

  1. The get() function is much like getline() but rather than read and discard the newline character, get() leaves that character in the input queue.
  2. get() leaves the delimiter in the queue thus letting you able to consider it as part of the next input.

Explanation:
cin.getline() reads input up to β€˜\n’ and stops

cin.get() reads input up to β€˜\n’ and keeps β€˜\n’ in the stream

For example :

char str1[100];
char str2[100];
cin.getline(str1 , 100);
cin.get(str2 , 100);
cout << str1 << " "<<str2;

input :
1 2
3 4
output 1 2 3 4 // the output expexted

When reverse them
For example :

char str1[100];
char str2[100];
cin.get(str2 , 100);
cin.getline(str1 , 100);
cout << str1 << " "<<str2;

input :
1 2
3 4
output 1 2 // the output unexpexted because cin.getline() read the β€˜\n’

Usage:
If you are talking about the newline character from a console input, it makes perfect sense to discard it, but if we consider input from a file, you can use as β€œdelimiter” the beginning of the next field.

Hope, this would help.
Give a like, if you are satisfied.

1 Like