Query in video 2D arrays

Please watch the video :
/2D Arrays/Reading a List of Strings/

at 23 seconds bhaiya said something about “to consume the enter while taking n as input”

Please explain this in “detail”… I faced a related problem before?

hello @prerak_semwal

after reading n(the number of input), \n (new line character) will remain inside buffer so to remove it we have to use cin.get()

@aman212yadav

then why it doesn’t affect this:-

#include
using namespace std;
int main()
{
int a,b;
cin>>a;
cin>>b;
cout<<a;
cout<<b;

return 0;
}

  • is automatically deleted by this platform!

we are reading two consecutive int thats why.

the issue arises when we read int and then a character or string becuase in buffer we left with \n just after reading an int and when we try to read next input as char/string we get \n (which is char ) so compiler treats it as new input.

but for two consective int the issue dosent arises becuase \n is not an int so compiler treats it as delimiter and read next element of buffer

@aman212yadav
hmm… I implemented following two:-

#include
using namespace std;
int main()
{
int a;
char b[10];
cin>>a;
cin.getline(b,10);
cout<<a;
cout<<b;

return 0;
}

#include
using namespace std;
int main()
{
int a;
char b[10];
cin>>a;
cin>>b,;
cout<<a;
cout<<b;

return 0;
}

#include
using namespace std;
int main()
{
int a;
char b;
cin>>a;
cin>>b,;
cout<<a;
cout<<b;

return 0;
}

#include
using namespace std;
int main()
{
int a;
char b[10];
cin>>a;
gets(b);
cout<<a;
cout<<b;

return 0;
}

It seems it’s happening only with cin.getline() and gets() . right ?

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.