0

I'm trying to write a C list filtering function that receives a country string, traverses the list and deletes all nodes with node->country == country. The problem is that node->country strings end with '\n' (because it's being read from a csv file) and therefore strcmp(node->country, country) never equals zero.

How would I solve this? I first thought about appending '\n' to country but that would probably raise more memory problems. Also thought about strstr but I don't really know how to work with that.

Thanks for any suggestions.

melpomene
  • 84,125
  • 8
  • 85
  • 148
returnNULL
  • 25
  • 7

2 Answers2

2

As you are using strcmp, let's assume some C-style code:

node->country[strcspn(node->country, "\n")] = '\0';

This will alter your node->country value and terminate your string right before a new line (if any).

melpomene
  • 84,125
  • 8
  • 85
  • 148
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

Suggested alternatives:

  1. Precompute

    size_t len_of_country = strlen(country)
    

    and use

    (strncmp(country, node->country, len_of_country) == 0 &&
     (node->country[len_of_country] == '\n' || 
     node->country[len_of_country] == '\0'))
    

    as the match criterion.

  2. Same as (1.), but if the latter case, also set node->country[len_of_country] to 0 for later use.

  3. Make your CSV parser chomp the trailing newline when reading the country string from the file, and just use strcmp().
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • For option 3, how do I "chomp" the newline, using 1. ? – returnNULL May 25 '18 at 18:47
  • @returnNULL: Well, that depends on what you use to read you CSV file, which is a detail I don't have. If you're not using any library, consider doing so. There are at least [two](https://github.com/fiksu/rcsv/network) different [ones](https://github.com/robertpostill/libcsv/network) on GitHub and a (more classic?) [libcsv](https://sourceforge.net/projects/libcsv/), but I haven't tried them myself. – einpoklum May 25 '18 at 18:51
  • I tried option 1 with node->country = "France\n" and country = "France" and it returns 0, isn't it supposed to return 1? And the parser simply uses a strtok – returnNULL May 25 '18 at 18:56
  • @returnNULL: Oh, sorry, I mis-copy-pasted. I meant that after the `strncmp()` passes you also check the last character. See edit. – einpoklum May 25 '18 at 18:58