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.
CodePudding user response:
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";