c++arrayscingetline

Why does cin.getline() not read the last character when it reads my input and assigns it to a char array?


I am new to C++. I don't understand why the cin.getline() that I use to assign characters to a character array does not return the "correct" number of characters.

For instance, I have:

char st[5];
cin.getline(st,5);
cout<<st;

My understanding is that getline(st, 5) reads 5 characters from my keyboard and assigns them to st. So, suppose I run the above code block and enter "abcde". I would now expect st to hold "abcde", but it only holds "abcd" instead. The last character, e, gets cut off. Why is this happening?


Solution

  • My understanding is that getline(st, 5) reads 5 characters from my keyboard and assigns them to st.

    That is incorrect. It will read and store up to 4 characters max, and then store a null terminator. Just as the buffer itself must include room for the terminator, the size you pass in must also account for the terminator.

    The last character, e, gets cut off.

    It is not "cut off". It is simply not read to begin with. It is still sitting in cin's input buffer, waiting for a subsequent read operation to extract it.