Skip to content
TheChatArchiveThe Chat Archive
Microsoftwizardlm-13b· MicrosoftHugging Face Arena Human Preference 55K

I'm calling sscanf in C like this: sscanf(str, "bleh [%s]", arg); But if str is "bleh…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with vicuna-33b’s answer.
  1. User

    I'm calling sscanf in C like this: sscanf(str, "bleh [%s]", arg); But if str is "bleh [foo]", arg ends up as "foo]", not "foo". How do I correct this?

  2. Microsoft Assistant

    The problem is that the %s format specifier in sscanf expects a null-terminated string. In your case, the string in str is not null-terminated, so sscanf is not able to correctly parse it.

    To fix this, you can use the strcspn function to find the length of the string up to the first whitespace character, and then use sscanf with that length. Here's an example:

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "bleh [foo]";
        char *arg;
    
        // Find the length of the string up to the first whitespace character
        int len = strcspn(str, " \t\n");
    
        // Use sscanf with the length found by strcspn
        arg = str;
        sscanf(str, "bleh [%.*s]", &len, arg);
    
        printf("arg: %s\n", arg);
    
        return 0;
    }
    

    In this code, strcspn(str, " \t\n") finds the length of the string up to the first whitespace character. Then, sscanf(str, "bleh [%.*s]", &len, arg) reads the string "bleh [foo]" into arg, where len is the length of the string up to the first whitespace character. The .* in the format string means "match and discard the whole string".

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.