0

I have been trying to look for the answer to this question...but I haven't found it.

I have to parse an string in C in the way

Send XMb to eth0 eth1 wlan0 with rates 1 2 3

Send YMb to em1 wlan0 with rates 2 5

The thing is that I don't know the amount of elements I'll have in the list..therefore I don't know how many %s to put.

Thanks in advance.

1
  • If it is a string, simply tokenize the string based on the delimiter (in this case a space). Commented Feb 12, 2014 at 18:28

2 Answers 2

1

One possible solution is to read in the whole command and process it later. For example, you can tokenize your command string with delimiter ' ' (a whitespace). Then you look for all tokens between "to" and "with", which will be your destination of sending. Similarly, you can find the rates by looking for tokens after "rates".

Sign up to request clarification or add additional context in comments.

Comments

1

Another possibility is to parse the string with sscanf (or fscanf) and make use of the %n specifier, which stores the number of characters processed up to that point.

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

int main() {

  char str[] = "Send XMb to eth0 eth1 wlan0 with rates 1 2 3";
  char val[100];
  char c[2];
  int n = 0, m;

  if (sscanf(str, "Send %1[XY]Mb to %n", c, &n) == 1) {

    printf("%s\n", c);

    while (sscanf(str+n, "%99s%n", val, &m) == 1) {
        n += m;
        if (strcmp(val, "with") == 0)
            break;
        printf("%s\n", val);
    }

    sscanf(str+n, " rates%n", &m);
    n += m;

    while (sscanf(str+n, "%99s%n", val, &m) == 1) {
        printf("%s\n", val);
        n += m;
    }
  }

  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.