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.

1
  • 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. Commented Oct 15, 2022 at 18:55

1 Answer 1

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";

Sign up to request clarification or add additional context in comments.

1 Comment

Note strtok will happily output empty tokens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.