why extra getchar() makes it accepted in ques DIRECTI

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
//freopen(“input.txt”,“r”,stdin);
//freopen(“out.txt”,“w”,stdout);
int t,n,k,i,last,x;
char a[41][100];
cin>>t;
while(t–)
{
i=0;
cin>>n;
getchar();// WHY THIS???
x=n;
while(n–)
{
gets(a[i++]);
}
printf("Begin on ");
last=strlen(a[x-1]);
for(i=0;i<last;i++)
{
if(a[x-1][i]==‘o’ && a[x-1][i+1]==‘n’ && a[x-1][i+2]==’ ')
{
k=i+3;
break;
}

		}
		for(i=k;i<last;i++)
		{
			printf("%c",a[x-1][i]);
		}
		printf("\n");
		for(i=x-2;i>=0;i--)
		{
			last=strlen(a[i]);
			for(int z=0;z<last;z++)
			{
				if(a[i][z]=='o' && a[i][z+1]=='n' && a[i][z+2]==' ')
				{
					k=z+3;
					break;
				}
			}
			if(a[i+1][0]=='R')
			printf("Left on ");
			if(a[i+1][0]=='L')
			printf("Right on ");			
			for(int p=k;p<last;p++)
			{
				printf("%c",a[i][p]);
			}
			printf("\n");		
		}
		printf("\n");
	}
return 0;	
}

cin>>n;
getchar();

It’s because the getchar(); consumes the newline character that you enter after
entering the value of n on the console. Otherwise, the newline becomes the part
of the first string you type in.

2 Likes

yep, both cin and scanf have this “leaving delimiter” habit. And if file is not linux made, take care of the \r character too!