0

The string I am trying to parse is called str1, and it contains PRETTY_NAME="Ubuntu 20.04.1 LTS"

The goal is to have one variable contain PRETTY_NAME, and the other contains Ubuntu 20.04.1 LTS. I have declared both variables as char *var1, *var2

This has to be done with the sscanf function in C.

My current code looks like: sscanf(str1, "%s[^=]^s", var1. var2); The output I am receiving is that both var1, and var2 return (null).

What am I doing wrong?

4
  • 1
    That line can not possibly compile. Please post real code, see How to create a Minimal, Reproducible Example. Commented Jan 25, 2021 at 0:19
  • 2
    char *catch_str; That's an uninitialized pointer, so sscanf(str1, "%s %s", catch_str, ...); is undefined behavior. Either change it to char catch_str[100]; or allocate it dynamically. Same goes for my_str, then after that you'll still have to fix the sscanf format string. Commented Jan 25, 2021 at 0:26
  • Thank you. Could you provide any hints as to what I am doing wrong with my sscanf format? Commented Jan 25, 2021 at 0:49
  • 1
    You probably want something like "%[^=]=\"%[^\"]\"". Don't forget to check the return value of sscanf to make sure that parsing succeeded. Commented Jan 25, 2021 at 0:56

1 Answer 1

1

the %s matches the entire string terminates at white space or \0 including = in that case, you can't use that here, and you haven't initialized any of your char buffer with a size which leads to crash or undefined behavior. here is a simplified parser.

void parse(const char* str, char* pretty, char* release) {
    int pretty_end, start, end;
    sscanf(str, "%*[^=]%n=\"%n%*[^\"]%n\"", &pretty_end, &start, &end);
    
    strncpy(pretty, str, pretty_end);
    pretty[pretty_end] = '\0';
    
    strncpy(release, str+start, end-start);
    release[end - start] = '\0';
}

int main() {

    const char* str = "PRETTY_NAME=\"Ubuntu 20.04.1 LTS\"";
    char pretty[256];
    char release[256];
    parse(str, pretty, release);

    return 0;
}

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

1 Comment

Nice use of "%n", yet better to first end = 0 and test after sscanf() that it is not zero before using pretty_end, start, end.

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.