简体   繁体   中英

loop printing when it should pass (C)

I am trying to print unique files from a linked list, basically I have a char* check that I compare to the currentfile and if it is different then I change the pointer to the new file and print it, I have 5 instances within 2 unique files, yet when I run the loop it prints out 5 files (1 file twice and the other file 3 times) instead of just printing each file once, how can I fix this?

for (ptr = head; ptr != NULL; ptr = ptr->next){
    if(ptr->fileName != check){
        check = ptr->fileName;
        printf("%s\n", check);
    } 
    else{
        continue;
    }
}

In C, you can't do if ( str1 != str2 ) . You have to use the strcmp() functions.

Instead of

if(ptr->fileName != check){

you would have

if ( strcmp(ptr->fileName, check) != 0 ) {

strcmp returns 0 if the strings are equal, and -1 or 1 depending on whether str1 or str2 is greater than the other.

You have to store the files that you have printed in some where. In each iteration, you need to look in your store to see if that file is already printed or not.

Consider the sequence of files:

  1. File1
  2. File2
  3. File1
  4. File2
  5. File1

It will be printed 5 times.

If it is

  1. File1
  2. File1
  3. File1
  4. File2
  5. File2

If will be printed 2 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM