need help with spoj problem broken

problem link



char ip[MAX];
int main()
{
	int m,hash[400];
	int max=-1;
	int l=0,r=0;
	scanf("%d",&m);
	while(m!=0)
	{
		memset(hash,0,sizeof(hash));
		scanf(" %[^\n]s",ip);
		strcat(ip,"0");
		int len=strlen(ip);
		l=r=0;
		max=-1;
		int dist=0;
		while(l<len)
		{
			while(r<len && dist<=m)
			{
				if(hash[(int)ip[r]]==0)
					dist++;
				hash[(int)ip[r]]++;
				r++;
			}
			
			int temp=r-l-1;
			if(temp>max)
				max=temp;
			if(hash[(int)ip[l]]<=1)
				dist--;
			hash[(int)ip[l]]--;
			l++;
		}
		int temp=r-l-1;
		if(temp>max)
			max=temp;
		printf("%d\n",max);
		scanf("%d",&m);
	}
}

The code is not considering the last character of the input. So I added a “0” at the end. Now this sentinel value is not being read, giving me Correct Answer. My question is how to fix the code so that the sentinel value is not required? It definitely is causing my code to run a bit slow (though AC).

Any pointers??