3

I have a string with the following format:

start 123

I am parsing it that way:

if (strstr(line, "start") == line) {
    int number = -1;

    if (sscanf(line + strlen("start "), "%d", &number) == 1) {
        printf("start %d\n", number);
    }
}

Is there any better way in C?

1
  • 1
    You could write your own parser or try using strtok(). sscanf() is probably the best way though. Commented Apr 18, 2013 at 13:24

2 Answers 2

10

yes you can use only this:

if (sscanf(line, "start %d", &number ) == 1) {

no need for

if (strstr(line, "start") == line) {

any more

If you want to check more: Check that there is no extra characters after the number , then you can use the following format:

char c;
if (sscanf(line, "start %d%c", &number,  &c) == 1) {

Note: the above formats (and even yours) do not check that there is only 1 space between "start" and the number. so if your string is something like "start \t 45" then the if will return true

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

2 Comments

@Петр Широков note that this format do not check that there is only 1 space between "start" and the number.
That is ok. In my case the number of spaces does not matter.
0
if (strstr(line, "start") == line) {
    int number = -1;

    if (sscanf(line, "%*s %d", &number) == 1) {
        printf("start %d\n", number);
    }
}

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.