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