sscanf不能正常工作?

Chr*_*oba 2 c scanf

我正在尝试解析一个URL,并编写了这段代码:

#include <stdio.h>

int main() {
    char host[100];
    char port[100];
    char path[100];
    char prot[100];
    char* url = "https://google.com:8000/foobar";
    sscanf(url, "%s://%s:%s/%s", prot, host, port, path);
    printf("Protocol: %s\n", prot);
    printf("Host:     %s\n", host);
    printf("Port:     %s\n", port);
    printf("Path:     %s\n", path);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,它输出:

Protocol: https://google.com:8000/foobar
Host:     å0&TFaa
Port:     
Path:
Run Code Online (Sandbox Code Playgroud)

我不确定为什么将所有字符串放入协议变量中,而不是将正确的部分放入每个变量中.有任何想法吗?

R S*_*ahu 8

sscanf很贪心.它尽可能多地读取字符.

将其更改为使用:

char* url = "https://google.com:8000/foobar";
sscanf(url, "%[^:]://%[^:]:%[^/]/%s", prot, host, port, path);
Run Code Online (Sandbox Code Playgroud)


Ed *_*eal 6

sscanf()与格式"%s"是贪婪的,因此会尽可能地匹配.

您还需要检查sscanf()它返回的返回值.

请查阅手册页.也许这种格式"%[^:]"正是您所寻找的.