This code is not working as the comparison is not being done. Why?
All names get past the if
.
printf("Enter Product: \n");
scanf("%s", &nameIt2);
printf("Enter Description: \n");
scanf("%s", &descriptionI);
printf("Enter Quantity: \n");
scanf("%d", &qtyI);
printf("Enter Order Quantity: \n");
scanf("%s", &ordqtyI);
while (fscanf(fp4, "%s %s %d %s\n", &namet2, &description2, &qty2, &ordqty2) != EOF){
if(namet2 != nameIt2)
fprintf(fpt2, "%s %s %d %s\n", &namet2, &description2, qty2, &ordqty2);
}
This question is related to
c
string
comparison
To compare two C strings (char *
), use strcmp()
. The function returns 0
when the strings are equal, so you would need to use this in your code:
if (strcmp(namet2, nameIt2) != 0)
If you (wrongly) use
if (namet2 != nameIt2)
you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).
For comparing 2 strings, either use the built in function strcmp()
using header file string.h
if(strcmp(a,b)==0)
printf("Entered strings are equal");
else
printf("Entered strings are not equal");
OR you can write your own function like this:
int string_compare(char str1[], char str2[])
{
int ctr=0;
while(str1[ctr]==str2[ctr])
{
if(str1[ctr]=='\0'||str2[ctr]=='\0')
break;
ctr++;
}
if(str1[ctr]=='\0' && str2[ctr]=='\0')
return 0;
else
return -1;
}
You need to use strcmp
:
strcmp(namet2, nameIt2)
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
You are currently comparing the addresses of the two strings.
Use strcmp to compare the values of two char arrays
if (strcmp(namet2, nameIt2) != 0)
if(strcmp(sr1,str2)) // this returns 0 if strings r equal
flag=0;
else flag=1; // then last check the variable flag value and print the message
OR
char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);
for(int i=0;str1[i]!='\0';i++)
{
if(str[i]==str2[i])
flag=0;
else {flag=1; break;}
}
//check the value of flag if it is 0 then strings r equal simple :)
You try and compare pointers here, not the contents of what is pointed to (ie, your characters).
You must use either memcmp
or str{,n}cmp
to compare the contents.
To answer the WHY in your question:
Because the equality operator can only be applied to simple variable types, such as float
s, int
s, or char
s, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character strings character by character.
Source: Stackoverflow.com