How to parse simple string in C?

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?

Upvotes: 3

Views: 6973

Answers (2)

MOHAMED
MOHAMED

Reputation: 43588

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

Upvotes: 10

BLUEPIXY
BLUEPIXY

Reputation: 40155

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

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

Upvotes: 0

Related Questions