Hello all,
I have spent the better part of today trying to figure this out.
I've asked elsewhere and searched around a lot but I cannot figure it out.
I have searched around on here as well as other sites for potential explanations for this, and I believe it is something to do with the \n or the \0 that is added when using fgets. Maybe or maybe not.
At the moment I have a list of words (one per line) in a text file that I read into an array, I use the following code to read the file into an array:
Code:
int i = 0;
while(fgets(buffer,sizeof buffer, fileIn) != NULL) {
list[i] = malloc(strlen(buffer) + 1);
strcpy(list[i], buffer);
i++;
}
This works as intended, reading the file into the array.
I then ask the user to input a word... Also using fgets.
Code:
printf("Please enter the word to compare.\n");
fgets(compword, sizeof(compword),stdin);
I then compare the two and print the result of the comparison...
Code:
int result = strcmp(list[0], compword); printf("Result: %d\n", result);
However the result, I am using the first word which is 'test' is 3... Before I was using a scanf to take the user input, and the result would be 13, so I thought I would try using the same way as the file is read in, and the result of the comparison is now 3.
I know that fgets adds the \n to the end of strings, which is what I think caused scanf to compare and return 13, but now I don't know what could be the difference? In the text document they are just the words, no extra spaces etc.
Can anyone help with this? I'm really not sure anymore what could be causing it. If you can't is there any way I could do it so that they do equal the same thing? :/
Also, I am on a mac computer using the terminal.
I have also tried it in xcode now and the result is the same.