我正在尝试解析一个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)
我不确定为什么将所有字符串放入协议变量中,而不是将正确的部分放入每个变量中.有任何想法吗?
sscanf很贪心.它尽可能多地读取字符.
将其更改为使用:
char* url = "https://google.com:8000/foobar";
sscanf(url, "%[^:]://%[^:]:%[^/]/%s", prot, host, port, path);
Run Code Online (Sandbox Code Playgroud)