Reputation: 53
I am reading input from different text files. These text files are integers that are either separated by a space, a new line, or a combination of spaces and new lines. I want to convert these strings to integers, and use these integers for a sorting algorithm.
char *line = malloc(BUF_SIZE);
char *token;
struct list* l = list_init();
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
printf("%s", token);
}
list_cleanup(l);
return 0;
What is wrong with this, it that it just prints the first element of each line. It doesn't handle multiple elements per line.
Thanks in advance.
Upvotes: 3
Views: 833
Reputation: 12742
You need to have loop
to process all the tokens. strtok
will return NULL
once all the tokens are over.
Example:
while (fgets(buf, BUF_SIZE, stdin)) {
token = strtok(buf," \n");
while (token != NULL) {
printf("%s", token);
token = strtok(NULL," \n");
}
}
Upvotes: 6