2

I need to convert a comma separated string to an array in proc, I am getting the string in:

while ((ch = getopt(argc, argv, "do:c")) != EOF)
{
    switch (ch) 
    {
        case 'c':
            get_order_type(optarg);

get_order_type(optarg) is comma separated string like 30,31,32 I need to get each string.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
pri
  • 119
  • 1
  • 9
  • 2
    Possible duplicate: http://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c – totoro Apr 13 '16 at 13:14

2 Answers2

1

The function you are looking for is strtok. That means String Tokenizer.

I think this will work for you:

  char str[] = get_order_type(optarg);
   const char s[2] = ",";
   char *token;

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

   /* walk through other tokens */
   while( token != NULL ) 
   {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

Anyway, here you have the documentation for the method.

Hope it helps!!

0
#define max_strln 30

#define max_str_no 20

char input[] = get_order_type(optarg);
char *str;
int i_ctr;
char arr[max_str_no ][max_strln];    

for(i_ctr = 0,str = strtok(input,","); str!= NULL; i_ctr++, str= strtok(NULL,","))
  {
    strcpy( arr[i_ctr], str);
  }

Explanation:

we take comma separator string in "input" variable and tokenize that variable by delimiter ( here comma). strtok return string which is separate by delimiter (here comma is delimiter). finally we copy that string into array using copy function.

Adesh
  • 34
  • 4
  • copy "get_order_type(optarg)" in str_wth_comma variable – Adesh Apr 11 '16 at 06:07
  • While this code may answer the question, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Apr 11 '16 at 09:25
  • Yes its ans of given question. strtok return string which is separated by delimiter (here comma is the delimiter). – Adesh Apr 13 '16 at 12:57
  • @TobySpeight : if u satisfied with ans plz accept it – Adesh Apr 14 '16 at 07:20
  • It is probably best to post something you've at least compiled - there's too many errors in the above to make a good answer. – Toby Speight Apr 14 '16 at 07:27