Im using C89
I am writing a small program for practice and I thought the logic I used is correct, yet it is printing different results than what I want.
My program is as follows:
#include <stdio.h>
#include <string.h>
struct animal
{
char species[30];
char breed[30]; };
void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed);
int main(void)
{
struct animal unique[10] = { {"Cat", "Persian"}, {"Dog", "Collie"},
{"Bird", "Conure"}, {"Dog", "Lab"} };
int i;
int count = 4;
addAnimal(unique, &count, "Cat", "Calico");
addAnimal(unique, &count, "Bird", "Budgie");
addAnimal(unique, &count, "Dog", "Lab");
for( i = 0; i < count+1; i++)
printf("%s, %s\n", unique[i].species, unique[i].breed);
}
And I have this function:
void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed)
{
int i, k = 0;
k = *count;
for( i = 0; i < k; i ++)
{
if( strcmp(unique[i].species, newspecies) && strcmp(unique[i].breed, newbreed) )
{
printf("both match\n");
/* do nothing */
}
else
{
*count = *count + 1;
strcpy(unique[*count]. species, newspecies);
strcpy(unique[*count]. breed, newbreed);
}
}
}
Basically I want the function to add the given names if they do not exist already, and do nothing is they do exist.
What I keep getting (without all the extra print statements) is
Cat, Persian
Dog, Collie
Bird, Conure
Dog, Lab
,
Cat, Calico
Bird, Budgie
Dog, Lab
which is wrong. And I have no idea why that comma is printing either.
change to
void addAnimal( struct animal unique[], int *count, char* newspecies, char* newbreed){
int i, k = *count;
for( i = 0; i < k; i++){
if( strcmp(unique[i].species, newspecies)==0 && strcmp(unique[i].breed, newbreed)==0 ){
printf("both match\n");
return ;
}
}
//added only once (Rather than if it does not match the data for each)
strcpy(unique[*count].species, newspecies);
strcpy(unique[*count].breed, newbreed);
*count = *count + 1;
}
and at main
for( i = 0; i < count; i++)
printf("%s, %s\n", unique[i].species, unique[i].breed);