# Thread: comparing strings

1. ## comparing strings

In this function, I am reading in a 'license plate' and comparing to all 'licence plates' in my array. If there is a match, then null that part of the array (the car is leaving). It seemed to work fine but I discovered that if the plate number began with 'd' then the program nulls all plate numbers beginning with d. My for loop looks okay but I am not sure how to fix it. Suggestions???

void Delcar (char cars [MAX][PLATE])//function to delete a car
{

int i,x;
int counter;
counter=CINIT;
char tarray[PLATE]={'\0'};
char ch;

do
{
scanf("%s",tarray);

{for (x=LINIT;x<MAX;x++)

for (i=LINIT;i<=PLATE;i++)

{
if (cars[x][i]==tarray[i])
{
cars[x][i]='\0';
printf("Car left space %d\n",x+1);

counter++;
}

break;

}
}
}
while (counter<=CINIT);

Options(); //function to call main menu
scanf("%c",&ch);

}

2. You don't compare strings with ==

Well, OK, so you can in C++, but not C.

You must use either strcmp (string compare) or stricmp (insensitive string compare)

instead of "if (cars[x][i]==tarray[i])"

use "if(strcmp(cars[x], tarray)==0)" (if it equals 0, they're the same)

or, to make it fancy do "if(!strcmp(car[x], tarray))"

3. Works fine now.

Thanks!

4. I personally loathe un-natural return values, and even though strcmp is really a sort - friendly function, it is commonly used for "exact matching". A wrapper function does the trick:

Code:
```
int Identical( char s[], char t[] ) {

if( strcmp( s, t ) == 0 )
return 1;

return 0;
}

Of course the preferred may be:

bool Identical( char *s, char *t ) {

return strcmp( s, t ) == 0 ? true : false;
}```

Popular pages Recent additions