Search code examples
c++buffercin

buffer cleaning in getline function


I understood that cin.getline() function doesn't clean the buffer and for example in the code below the program skip the line 4:

char name[10];
char id[10];
std::cin >> name;
std::cin.getline(id,10);
std::cout << name << std::endl;
std::cout << id << std::endl;

the output (if I enter "Meysam" as name variable):

Meysam

so because the cin.getline() doesn't clean the buffer then we can't enter the id variable but if we use two cin.getline() like below we can enter name and id variable.

char name[10];
char id[10];
std::cin.getline(name,10,'\n');
std::cin.getline(id,10,'\n');
std::cout << name << std::endl;
std::cout << id << std::endl;

here is the output ( we entered Meysam and 12345 as name and id):

Meysam
12345

but why is this? I mean because the cin.getline() doesn't clean the buffer we should be able to enter the name variable, but then the program should skip the next cin.getline() which is for id, because the buffer is already filled by previous cin.getline().NO? I want to know where I didn't understand correctly Thank you.


Solution

  • In the first case, cin>>name does not consume the newline character and it is still there in the buffer. The fourth line is not skipped, instead cin.getline() reads the \n in the buffer and stops reading further as the default delimiter of getline in \n. As such the id only contains the newline character.

    In the second case, cin.getline() reads the complete line and stops after consuming the newline character. There is nothing left in the buffer now, so the next cin.getline() reads your id.

    Refer here