PriyankaJhamb

Are you confused about using cin and cin.getline both in a single program? 

Let us discuss first what is difference between cin and cin.getline… Both cin object and cin.getline function are basically used for taking input from the user.

So, what’s difference?

cin>>name_of_the_variable;
cin.getline(name_of_the_variable, string_length, optional_delimiter);

Example:

#include <iostream>
using namespace std;
int main() {
char name[10];
cout<<"Input: ";
cin>>name;
cout<<"Output: "<<name<<endl;
}

Output image

#include <iostream>
using namespace std;
int main() {
char name[10];
cout<<"Input: ";
cin.getline(name, 10);
cout<<"Output: "<<name<<endl;
}

Output image

Now Question is why this is happened?

Because cin does not take input after it sees any space, any tab, any new line but cin.getline stops taking input when it sees any delimiter i.e default delimiter is \n (new line). One more difference is there. let us see example first:)

#include <iostream>
using namespace std;
int main() {
char name[10];
cout<<"Input: ";
cin>>name;
cout<<"Output: "<<name<<endl;
}

Output image

#include <iostream>
using namespace std;
int main() {
char name[10];
cout<<"Input: ";
cin.getline(name, 10);
cout<<"Output: "<<name<<endl;
}

Output image

So, now I hope you have got it: so every character array automatically puts ‘\0’ at last index after our string is complete. now again sees this when we are putting one more than array size:

#include <iostream>
using namespace std;
int main() {
char name[10];
cout<<"Input: ";
cin.getline(name, 11);
cout<<"Output: "<<name<<endl;
}

Output image

Difference in tabular form:

cin cin.getline()
When it encounters space, tab or new line, it stops to take input into the buffer for particular variable. It stops when it encounters optional delimiter. By default, optional delimiter is new line ‘\n’.
It does not take any argument. It takes an argument of length which we can give any but less than (variable_array_length +1) only.
cin is basically an object in C++ of the class istream that accepts input from the standard input device. getline is a standard library function that is used to input a string or reads a line from input stream

Simple Program to explain the problems that we usually get into while using both cin and cin.getline

#include <iostream>
#include<limits>
using namespace std;
int main() {
char name[2], nameother[10];
cout<<"Program starts here: "<<endl;
cout<<"Enter your name: "<<endl;
cin>>name;
cout<<"Your name is : "<<name<<endl;
}

image

References Section:

https://pediaa.com/