HOLES: scanf vs getchar, please help

Hey guys, in the below code getchar in the loop is taking the value of scanf for the 1st iteration… i.e. on running d code lyk input
3
den instead of asking the character it is printing 0 value in output(k’s value) and den it is running correctly…
So plz tel me y for the 1st iteration it is nt working properly???
y scanf is nt working in front of getchar if it is used in loop??
plzz help

#include<stdio.h>
main()
{
	int n,k;
	char c;
	scanf("%d",&n);
	while(n--)
	{
		k=0;
		while((c=getchar())!='\n')
		{
			if(c>='A' && c<='Z')
			{
				if(c=='A' || c=='D' || c=='O' || c=='P' || c=='Q' || c=='R')
					k=k+1;
				if(c=='B')
					k=k+2;
			}
		}
		printf("%d\n",k);
	}
	return 0;
}

please use the code option from toolbar - http://i.imgur.com/ODZlB.png (you can edit your question)

It’s because scanf("%d") to not read '\n', so your first getchar() reads that character. You can do 2 thing:

  • read n as scanf("%d\n",&n);
  • or add getchar(); before while
2 Likes