while I was going through a lecture on how to take string from the user, Prateek Bhaiya wrote the following code:
int main()
{
char a[][];
int n;
cin>>n;
cin.get();
for(int i=0;i<n;i++)
{
cin.getline(a,10);
}
return 0;
}
I couldn’t understand what is the use of writing cin.get() after cin>>n?
please explain in detail, in hindi, if possible.
Taking string from the user
@Tiwary725 when you take the input cin>>n it stops when it found any space or change in line that change in line (means ‘\n’) remains in input buffer so when you call cin.getline() directly to take your string input it will first read ‘\n’ which was in the input buffer and hence will not read your char so to take this ‘\n’ out of input buffer we have used cin.get() which will read ‘\n’ then we can call cin.getline().
Sir but cin. get() doesn’t read \n, but you are saying that cin.get will consume \n
@Tiwary725 yeah cin.get() will not read ‘\n’ but only when you called it with array and its size like cin.get(charArray,size) but it can consume ‘\n’ when you called it simply cin.get() without passing any array.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.