c - determining genders in a file

So, I'm a bit stuck here.
I'm supposed to make a program which will read data from a file to determine how many female and male adults of legal age exist in the file.

This is the best I could do:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>

int main()
{
	char b[1000];
	int sum;
	FILE *fptr;
	
	if ((fptr = fopen("adults.txt","r")) == NULL)
	{
       printf("Error! opening file");
       exit(1);
	}
	
	while (EOF != fscanf(fptr, "%[^\n]\n", b))
	{
    	printf("%s\n", b);
	}
	
   fclose(fptr); 
  
   return 0;	
}


So the output from the file looks something like this:
female 29
male 30
female 24
male 25
male 18
female 19

As for the determining the genders:
total females: 3 (whatever amount from the list in the file).
total males: 3 (whatever amount from the list in the file).

So, as you can see I'm fine with the output of the file in the input, but I'm not sure how to determine the amount of genders.

Someone plz help!
just keep adding stuff :)

you need to read into 2 variables gender and age both, when you do the scan..

int males = 0;
int females = 0;
const int legal = 18; //or whatever it is. we drinking, voting, driving, or something else?

...
while(things)
{
if(age >= legal)
{
if(strcmp(something, "male") == 0 )
male++;
else
female++; //if you trust your file and code, you can take this shortcut. if not be explicit.
//print something here ?? here, the age is legal, so you can print ..
}

}

//or print something here, total # of each that is legal perhaps summary?

Last edited on
I would read the file like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#define _CRT_SECURE_NO_WARNINGS

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

#define NUM_FIELDS  2

int main()
{
  char gender[7] = {0};
  int age = 0, male_count = 0, female_count = 0;
  FILE *fptr;

  if ((fptr = fopen("adults.txt", "r")) == NULL)
  {
    perror("Error! opening file");
    exit(1);
  }

  while (fscanf(fptr, "%6s %d", gender, &age) == NUM_FIELDS)
  {
    printf("Gender=%s\tAge=%d\n", gender, age);
    /*
      Now check the gender and inc the corresponding counter
    */
  }
  /* Print the stats*/
  fclose(fptr);

  return 0;
}
Topic archived. No new replies allowed.