The getchar() is used to read the character (after scanf()) which is a “new line” (\n) which isn’t removed from the input-buffer by the scanf(). This doesn’t give problems when using just cin>> and similar functions, but if you use getline() after it, the last "\ " character (enter or new line or some other carriage returns) is read and the program seems to skip over the whole command.
When you read unformatted input, like getline(), it reads input until a newline (\n) character is found.
So the scanf only reads the input number (no. of test cases in your cases), but leaves the “\n” after it.If you do not use getchar(), the following getline() will only read this “\n” and skip to next line.
You can try commenting out the getchar() and test it for better understanding like this at ideone.
After taking integer input using scanf() ‘\n’ is left in the stdin and when we take character input then instead of actual input ‘\n’ is taken as the input and is stored in the variable which causes problem.
So to prevent this getchar() is used to take ‘\n’ input and discard it and after ‘\n’ is removed from buffer then you can successfully take the desired string from the stdin.
For example:
If input is
5\nhelloworld
then scanf takes 5 as input,
\nhelloworld
and now when we take string input \n is stored leaving helloworld as it is in buffer or stdin and thus getchar() is used to take that ‘\n’ and then helloworld can be taken as input.