why using getchar() in the following program

#include <cstdio>

#include <cstdlib>

#include <iostream>

#include <string>

#include <set>

using namespace std;

int main()

{

int t;
scanf("%d",&t);
getchar();
while(t>0)
{
	t--;
	string line;
	getline(cin,line);
	line = line + " ";
	int prev = 0;	
	set<string> myset;
	int i = 0;
	while(line[i]==' ')
			i++;	
	prev = i;
	for(;i<(int)line.length();)
	{
		while(line[i]!=' ')
			i++;
		myset.insert(line.substr(prev,i-prev));
		while(line[i]==' ')
			i++;	
		prev = i;
	}			
	printf("%d\n",(int)myset.size());
}

}

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.

Take a look here and here for more clarification.

3 Likes

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.

Hope you understood…!! :slight_smile:

2 Likes

Good example, could have given new line for clarification like this

If input is

5\n
helloworld

then scanf takes 5 as input,

\n
helloworld

:slight_smile:

@mediocoder

Actually real input file is not like you mentioned on above comment as far what i saw on a competitive coding site!!

Still for explanation we may observe example in that way…!! :slight_smile:

Ok brothar, I did not know that, I thought it would be easy to understand, upvoting ur ans.

Cheers… !!