0

Sorry I'm not sure how to correctly word the problem I'm having. I'm taking the user's input which is unsigned char, let's say unsigned char array = "123 343 342 4235 87 34 398" and now I would like to have each number in that String divided by the space into a separate array

items[0] = 123 items[1] = 343 items[2] = 342

and so forth. How can I approach this?

I forgot to mention I'm compiling with Linux so tutorialspoint.com/c_standard_library/c_function_strtok.htm

Does not compile for me or work

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

this is indeed a common question, for example here: Tokenizing strings in C

but anyways, here is one answer:

#include <stdio.h>
#include <string.h>

int main(void) {
    const int maxParsed = 32;
    char array[] = "123 343 342 4235 87 34 398";

    char* parsed[maxParsed];
    char* token = strtok(array, " ");

    int numParsed = 0;
    int i;

    while(token) {
        parsed[numParsed] = token;
        token = strtok(NULL, " ");
        numParsed++;
        if(numParsed == maxParsed) { break; }
    }


    for(i=0; i<numParsed; i++) {
        printf("parsed string %d: %s \n", i, parsed[i]);
    }
}

EDIT: This code fails in the edge case where the input is non-empty and contains no delimiters. You should check for that condition if the first call to strtok() returns NULL.

Community
  • 1
  • 1
ezra buchla
  • 319
  • 2
  • 6
  • The edge case here is if the input only has one set of numbers with no space. Then your first `strtok` will return NULL and you won't have parsed anything. – Cameron Bielstein Oct 09 '14 at 22:57
-1

You want to use strtok in combinaison with atoi for retrieving integers

I adapted the library example from tutorialpoints.

#include <string.h>
#include <stdio.h>

int main()
{
   const char str[27] = "123 343 342 4235 87 34 398";
   const char s[2] = " "; //Your delimiter, here a singlespace
   char *token;

  /* get the first token */
  token = strtok(str, s);

  /* walk through other tokens */
  while( token != NULL ) 
  {
      printf( " %d\n", atoi(token) ); // atoi converting char* to int !

      token = strtok(NULL, s);
  }

  return 0;
}
Mekap
  • 2,065
  • 14
  • 26