0

I am currently working on a piece of code and I am not sure how to tackle this problem. Ill explain the situation:

The goal of this code is to make a "dynamic" matrix in C. Using "fgets" I get a char array, my code interprets the first line as a char array. However there are more lines I am at this point only interested in the first one, all the other lines just contain the information I need to store.

The reason why I am only interested in the first line is because it contains the information on how big the matrix needs to be to fit all the information below. The information comes in a pattern, it is always in the form of x,y. The x and y are not bound by each other, the x could be for instance 10 times smaller or greater then the y. Also the location of the information on the line is not set, it could be floating on the right of the screen or on the left.

Is there any form, like regex in java, that I could use to filter the information? For examples look for "," in the first line and when it is found check the right and left side from the "," all the way to the first white space and store those both values in a variable.

example:

[                   14,10            ]

the outcome would be then:

int rowSize = 14;
int columnSize = 10;
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
Kipt Scriddy
  • 743
  • 2
  • 14
  • 22
  • 2
    [Eliminate the white space](http://stackoverflow.com/questions/1458131/remove-extra-white-space-from-inside-a-c-string) first. – Robert Harvey Feb 22 '13 at 23:50
  • Good idea, so I had an idea. If I eliminate the white space first I will end up with an array which consists of 2 numbers seperated only by a ",". Is it possible then to split the array at the "," to finally end up with 2 numbers? – Kipt Scriddy Feb 23 '13 at 00:02
  • Am I correct if I say I need to use "strtok" for splitting the string into smaller strings? – Kipt Scriddy Feb 23 '13 at 00:13
  • 1
    http://stackoverflow.com/questions/2523467/how-to-split-a-string-to-2-strings-in-c – Robert Harvey Feb 23 '13 at 00:27

1 Answers1

1

Why not search for the first valid decimal character?

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

char *first_digit(const char *s)
{
    while (!isdigit(*s)) s++;
    return s;
}


int main()
{
    const char *line = "[             14,      10        ]";
    int n, k;

    const char *first = first_digit(line);
    const char *end;
    n = strtol(first, &end, 10);

    const char *second = first_digit(end);
    k = strtol(second, NULL, 10);

    printf("n, k = %d, %d\n", n, k);
    return 0;
}
  • Thank you for your answer! But I think I am going to stick with the plan suggested by Robert Harvey just for the fact learning benefit. – Kipt Scriddy Feb 23 '13 at 00:03