Reputation: 101
I'm trying to print these tokens but I keep printing (null) at the end. This is the null pointer but I thought I accounted for this in the while loop. Edit: Oh, I'm not trying to print the first string in input. I'm trying to print everything after the first input but I keep printing that (null)
input = strtok(input_buffer, "\n ")
while (input != NULL)
{
input = strtok(NULL, "\n");
printf("%s", input);
}
printf("\n");
Upvotes: 1
Views: 1845
Reputation: 1279
After separating a string your printing the string, so the previous string will be lose , so print the string before separate on next time.
input = strtok(input_buffer, "\n ");
while (input != NULL)
{
printf("%s", input);
input = strtok(NULL, "\n");
}
printf("\n");
Upvotes: 1
Reputation: 355
You are first assigning values to variable input and then printing it.Remember, you are changing the value of input inside while loop.Just interchange 4th and 5th line. Try this:
input = strtok(input_buffer, "\n ")
while (input != NULL)
{
printf("%s", input);
input = strtok(NULL, "\n");
}
printf("\n");
Upvotes: 1
Reputation: 1742
You can also use a for loop:
for(input = strtok(input_buffer, "\n ");input != NULL;input = strtok(NULL, "\n"))
{
// Print first.
printf("%s", input);
}
printf("\n");
Upvotes: 2
Reputation: 206567
Adjust the order of things a bit.
input = strtok(input_buffer, "\n ")
while (input != NULL)
{
// Print first.
printf("%s", input);
input = strtok(NULL, "\n");
}
printf("\n");
Upvotes: 2
Reputation: 34829
Switch the order of the printf/strtok in the loop, since you already have the first token from outside the loop
input = strtok(input_buffer, "\n ")
while (input != NULL)
{
printf("%s", input);
input = strtok(NULL, "\n");
}
printf("\n");
Upvotes: 2