gpt4 book ai didi

c - sscanf 不能正常工作?

转载 作者:行者123 更新时间:2023-12-02 05:36:48 24 4
gpt4 key购买 nike

我正在尝试解析一个 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;
}

但是,它输出这个:

Protocol: https://google.com:8000/foobar
Host: å0&TFaa
Port:
Path:

我不确定为什么它会将我的所有字符串放入协议(protocol)变量中,而不是将正确的部分放入每个变量中。有什么想法吗?

最佳答案

sscanf 是贪心的。它会读取尽可能多的字符。

将其更改为使用:

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

关于c - sscanf 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28508011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com