0

My problem is quite similar to the problem here: Trimming a trailing \0 from fgets() in C However, the suggested solution buffer[strcspn(buffer, "\n")] = 0; as I am using char ** to store the tokens

Here's my code:

char str[1024];
fgets(str, 1024, stdin);

const char s[2] = " ";
char *token;
char ** token_arr = malloc(100 * sizeof(char*));
int pos = 0;

token = strtok(str, s);

while( token != NULL) {
  token_arr[pos] = token;
  printf( "%d %s\n", pos, token );
  pos++;
  token = strtok(NULL, s);
}

int i = 0;
while (token_arr[i]) {
printf("%d %s \n", i, token_arr[i]);
i++;
}

Input: a b c d e

The printf in each loop is separated by a blank line, which I presume is due to the trailing \0 that is perhaps stored inside the token_arr. How can I remove it?

Thanks a lot

ETA: What I meant it each print loop is printing an unintended extra blank line.

appleline
  • 27
  • 4
  • 1
    *Every* string has a trailing `'\0'`. The OP of the linked question is confused. You both might have meant a trailing `'\n'`. The suggested answer is correct. Do that before splitting the line. – n. m. could be an AI Oct 15 '22 at 18:55

1 Answers1

2

Contrary to gets(), fgets() keeps the newline that you typed in after your input.

Since the newline is not in your list of tokens it is kept as a part of the last token, hence the empty line.

just replace const char s[2] = " "; with const char s[3] = " \n";

J.P. Tosoni
  • 549
  • 5
  • 15