-1

I've two character strings, one with the first line of a file (which is "WORKING"), and a second with the word "WORKING". The problem is that when I try to put them in an IF, it says they're not the same!

I've tried to read both of them with printf command but they're the same. I've also tried to use '\n' in the second string but there's not any change.

Here's the code, have a look:

FILE *fl;
fl=fopen("test.txt", "r");
char line_working[100];
fscanf(fl, "%s\n", line_working);
fclose(fl);
printf("%s", line_working);              //HERE IT PRINTS: WORKING
char* workinger="WORKING";
printf("\n%s", workinger);               //HERE IT ALSO PRINTS: WORKING
getch();
if(workinger==line_working){
    printf("OK");
    getch();
}

And nothing happens...

jlxip
  • 125
  • 1
  • 12

3 Answers3

3
if(workinger==line_working){

compares the pointers.

workinger is a pointer and the array line_working used in the expression (comparison) gets converted to the pointer to its first element, which is equal to &line_working[0]. So it does address comparison. But this is not what you want. Unfortunately, this comparison is perfectly valid in C. So compiler can't help you here.

Use strcmp() to compare C strings.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

== compares the pointer addresses.

To compare null-terminated character arrays (aka C-strings), use strcmp:

if(strcmp(workinger, line_working) == 0)
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

Your code does not compare the strings that you correctly try to compare with the assumption that the result should be they are equal, but the memory location where the strings are stored. By using '==' you do compare the value of workinger (which is a pointer so the variables value is a memory address) and line_working (which is an array so the corresponding value equals the memory address of the 1st element)

if (workinger==line_working)

To compare the strings that are stored at the corresponding memory locations you should make use of the string compare functions (see this question How do I properly compare strings? )

Community
  • 1
  • 1
Matthias
  • 3,458
  • 4
  • 27
  • 46