Cin and cin.getline does not work together

I tried using cin and cin.getline but the string does not get stored.
When I used cin to input string it worked but with cin.getline() it does not work
#include
#include
using namespace std;
int main() {
char s[5];
int k;
cin>>k;
cin.getline(s,5);
cout<<k<<s;

return 0;

}

Hi @prat98
In above code, the output is not printed as desired. Reason to this is an occupied Buffer. The “\n” character goes remains there in buffer after we enter k as input and press enter and read as next input s. So to handle this problem you have to use cin.ignore() like this :

int k;
cin>>k;
cin.ignore();
cin.getline(s,5);
cout<<k<<s;

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.