使用scanf[重复]忽略字符串的部分。

问题描述 投票:0回答:1

我有一个字符串的形式

"http://something.another.thing:13541/random-text.txt"

我想提取 "something.another.thing:13541" 的一部分,所以我用

sscanf(uri, "http://%s/%*s", host);

将指定的部分读入缓冲区 host. %*s 应该忽略字符串中在 / 对吗?

c scanf
1个回答
3
投票

问题不在于丢弃部分,你需要一个定界符。[^?]

试试

char *uri = "http://something.another.thing:13541/random-text.txt";
char host[266];

sscanf(uri, "http://%265[^/]", host); // %265 prevents buffer overflows
printf("%s\n", host);

由于一个主机不能包含超过255个字节+比如10个端口。char host[266]; 是你想要覆盖所有可能的情况。

另一个选择是用 getconf HOST_NAME_MAX 并将其传递给程序,如果你在一些linux下。

© www.soinside.com 2019 - 2024. All rights reserved.