im using borland

/*Write a function that will scan/read each line of a given text file
and determine whether a line is valid or invalid. A line is said to be valid
if and only if it satisfies the ff:
a. the line is composed only of characters a and b
b. the line contains an equal number of a's and b's
The function must display valid/invalid as the case may be*/

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <string.h>

void main(void)
{
	FILE *fp;
	char str[100];
	int i,stop,a,b;

	if((fp=fopen("detvalid.txt","rt"))!=NULL)
	{
	 while (!feof(fp))
	 {
		fgets(str,100,fp);
		stop=0;a=b=0;
		for(i=0;i<strlen(str)&&!stop;i++)
		{
			if(str[i]=='a')
			{
				a++;
			}
			else if(str[i]=='b')
			{
				b++;
			}
			else
			{
				stop++;
			}
		}
		 if (stop||a!=b)
		{
			printf("invalid\n");
		}
		else
		{
			printf("valid\n");
		}
	 }
	 fclose(fp);
	}
}

Recommended Answers

All 4 Replies

>it won't work the way i want it
So fix it. We're not the psychic friends network, here to solve all of you problems with a crystal ball and smile. You wrote the damn program (and it's very short!), so you should be able to figure out why it's not doing what you want.

I'll direct you here because you really need it.

Try adding this to your if statement:

if(str[i] == 'a')
			{
				a++;
			}
			else if(str[i] == 'b')
			{
				b++;
			}
			else if (str[i] == '\n')
			{
				//this will account for the newline
			}
			else
			{
				stop++;
			}

ruenahay pisti kang inatay kang dako dyosa2 pa kuno ungo diay to

ruenahay pisti kang inatay kang dako dyosa2 pa kuno ungo diay to

kjsdf kshdfk sfdfja weui dsggw dhcjk

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.