1

So when writing this code and showing the last token it comes with the line delimiter "\n", how do i take that out?

 while( fgets( c, MAX_viagens, f) != NULL ) {
    int i = 0;
    char *p = strtok (c, ":");
    char *array[6];

        while (p != NULL){
         array[i++] = p;
         p = strtok (NULL, ":");
        }
    printf ("%s\n", array[3]);
Ventura
  • 97
  • 12

1 Answers1

2

One simple way to achieve this is to add the new line character to the delimiters:

char *p = strtok (c, ":\n");
...
p = strtok (NULL, ":\n");

Or you could remove it before (removes last character, even if it is not '\n'):

if(c[0])
{
    c[strlen(c)-1] = '\0';
}
Osiris
  • 2,783
  • 9
  • 17
  • I think your first example is the way to go. But, `strlen` has an extra cost, so, for your second example, I'd do: `int len = strlen(c); if (len) c[len - 1] = 0;` – Craig Estey Nov 10 '18 at 01:10
  • @CraigEstey Yes it would be more efficient to call `strlen` only one time. But if you enable optimization I think the compiler should recognize it. – Osiris Nov 10 '18 at 01:12
  • @CraigEstey I changed it to a simpler check. – Osiris Nov 10 '18 at 01:20
  • I think that's a good idea. Because this: `#include char *c; void funny(char *ptr); int main(void) { for (int idx = 0; idx < strlen(c); ++idx) funny(&c[idx]); return 0; }` _doesn't_ optimize the `strlen` to a single call. Because it _can't--it has to assume `funny` can change the string and `strlen` will return a different value. Helping the compiler [rather than _relying_ on it] is good practice, IMO. – Craig Estey Nov 10 '18 at 01:26