According to the documentation of std::basic_istream::ignore
:
Extracts and discards characters from the input stream until and
including delim. ignore behaves as an UnformattedInputFunction
Its worth to mention that std::basic_istream::ignore
will block and wait for user input if there is nothing to ignore in the stream.
With this in mind, lets break down what your code does:
- the first time you call this function in your loop, it is going to
ignore the new line character that is still in the buffer from the
previous
cin>>t
operation. Then the getline
statment will wait and read a line from the user.
- The next time around, since there is nothing in the buffer to
ignore(as
std::getline
doesn't leave the new line character in the
buffer), it is going to block and wait for input to ignore. So
the next time the program block and waits for input, it is because
of the ignore()
function,not the getline
function as you would
have hoped, and the moment you provide an input(i.e you second test
case),one character from the input is going to be ignored.
- The next
getline
function will not block since there is something
in the buffer left by the previous ignore
function after it
ignores the first character of the input so getline
will read the
remaining string which will happen to be one character short.
- The process continues from step 2 until your loop terminates.
int t;
cin>>t;//this leaves new line character in the buffer
while(t--)
{
string arr;
cin.ignore();//this will ignore one character from the buffer,so the first time
//it will ignore the new line character from the previous cin input
//but next time it will block and wait for input to ignore
getline(cin,arr);//this will not block if there is something in the buffer
//to read
...
}
The solution would be to move the ignore
statement out of the loop and next to your cin>>t
statement. It's also better write ignore(INT_MAX,'\n');
in this case. You might also want to read this answer to see when and how to use ignore
.