0

I have to read the arguments that I introduce when I run a program on linux.

./myprog 10 20 30, 20 54 12, 31 42 51

I have a problem finding out how to separate the arguments into a substring and then that substring in other string.

10 20 30, 20 54 12, 31 42 51

I want to separate this string into another string with "," being the separator and then that substring to separate into another string with " " being the separator.

 a[0]="10 20 30"
 a[1]="20 55 12"
 a[2]="31 42 51"

Then I want it to be like that:

 b[0]="10" b[1]="20" b[2]="30" and so on...
Andrew
  • 63
  • 4
  • 4
    Possible duplicate of [Split string with delimiters in C](https://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c) – Matthew Kerian Dec 05 '18 at 06:26
  • 1
    In order to read your argument as a single string in Linux -- you must **quote** the string, e.g. `"10 20 30, 20 54 12, 31 42 51"` -- then you can split `argv[1]` on the `','` delimiters. Otherwise you end up with 9 program arguments (two of which have a `','` tacked onto the end) – David C. Rankin Dec 05 '18 at 07:21
  • 1
    Thank you everyone for your support! :D – Andrew Dec 06 '18 at 16:59

1 Answers1

0

Here I make this code to separate the arguments into a substring.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char *str = "10 20 30, 20 54 12, 31 42 51";
    char **a = calloc(sizeof(char*),strlen(str));
    int x = 0;
    int y = 0;
    int i = 0;

    while (str[i] != '\0')
    {
        x = 0;
        a[y] = calloc(sizeof(char),9);
        while(str[i] != ',' && str[i] != '\0')
        {
            a[y][x] = str[i];
            i++;
            x++;
        }
        y++;
        i += 2;
    }
    //this code below for test
    y--;
    for (int t = 0; t < y; t++)
            printf("%s\n",a[t]);

}

now try to make the other one :).

Holy semicolon
  • 868
  • 1
  • 11
  • 27