0

I would like help with my compare function under the removeNameCard function. Even though the print shows the same name, comparing them in an if statement is skipped.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 5

typedef struct
{
    int nameCardID;
    char personName[20];
    char companyName[20];
}NameCard;

NameCard inputRecord[MAX];
int I;
char* p;    

void removeNameCard()
{
    char* a;
    char* b;
    char value[20];
    NameCard temp[MAX];
    printf("Enter personName:\n");
    while ((getchar()) != '\n');
    fgets(value, 20, stdin);
    if (inputRecord[0].nameCardID != 0) {
        for (int x = 0; x < MAX; x++) {
            a = value;
            b = inputRecord[x].personName;
            printf(a);
            printf(b);
            if (value == inputRecord[x].personName) {
                for (int j = x; j < MAX; j++) {
                    inputRecord[j] = inputRecord[j + 1];
                }
                inputRecord[MAX - 1].nameCardID = 0;
                i -= 1;
                printf("The name card is removed\n");
                return;
            }
            else {
                printf("The target person name is not in the name card holder\n");
            }
        }
    }
    else {
        printf("The name card holder is empty\n");
    }   
}

My problem is that the value of a and b is not the same therefore when I compare it on the if statement it always skips. Is there a way to retrieve just the char value of a and b without the address?

FDL9
  • 1
  • 1

2 Answers2

3

You should not use == (equality operator) to compare strings because they compare the reference of the string, i.e. whether the two char pointers points to same position in memory or not. On the other hand, strcmp() method compares whether the value of the strings is equal or not..

  • What if the value of a and b has different lower and uppercase. Lets say a = sam and b = Sam, does strcmp still works? – FDL9 Oct 19 '21 at 08:09
  • strcmp() is case sensitive, if you want case insensitive comparision of two strings then you can use strcasecmp()...these are included in the #include – Chaitanya Vamsi Oct 22 '21 at 15:40
0

it seems like you have compared two strings inside if-condition. I mean you cannot equate two strings in if-condition, my suggestion is to try

strcmp(value,inputRecord[x].personName)==0

instead of using

value == inputRecord[x].personName 

in your code. even the strings have upper and lower case letters ,strcmp() function still works provided you include this(#include <string.h>)

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Arjun ANS
  • 1
  • 1