Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two strings in C? [duplicate]

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); } 
like image 962
user1955438 Avatar asked Jan 09 '13 10:01

user1955438


People also ask

Can I use == to compare strings in C?

Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.

How can you compare two strings in C?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.


1 Answers

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).

like image 194
Veger Avatar answered Sep 29 '22 05:09

Veger