3

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.

  • 1
    `buf` or `line`? – Spikatrix Apr 03 '19 at 13:11
  • Sorry, this was not clear. buf is the input. Line is where I want to store the tokens – Gideon Mooijen Apr 03 '19 at 13:15
  • 1
    That's why it's so important to create a [mcve] to show us. Please edit your question to include one. Also please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Apr 03 '19 at 13:17
  • 2
    `man 3 strtok` maybe? "the `strtok()` function breaks a string into a sequence of zero or more nonempty tokens. On the first call to `strtok()`, the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str must be `NULL`.". I don't see a loop for `strtok()` results. – Stefan Becker Apr 03 '19 at 13:18
  • the first thing that is wrong is the posted code does not compile! – user3629249 Apr 04 '19 at 17:26

1 Answers1

6

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");
    }
}
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44