使用 sscanf 也有些年头了,但总是有些困惑,今天整理一下,记录下来,备忘。
直接上代码吧。
#include
#include
int main(int argc, char *argv[])
{
// Number of variables scanned.
int n = -1;
// Demo source string
char s[256] = {"demo string\r\n"
"default via 192.168.0.1 dev eth0\r\n"
"https://192.168.0.101:18883\r\n"
"this is \t the \t\f 4th \t\t\v line.\r\n"
"this is the 5th line."};
// Line buffer
char l[5][64] = {0, 0, 0, 0, 0};
// Line number
int ln = 0;
// IP address buffer
char ip[16] = "0.0.0.0";
// URL buffer
typedef struct URL_STRUCT
{
char protocol[6];
char ip[16];
unsigned int port;
} url;
url demo_url = {"xxx", "0.0.0.0", 0};
// Single line buffer
char line_parts[5][16] = {0, 0, 0, 0, 0};
// Pointer to source string
char *p = s;
do
{
n = sscanf(p, "%[^\r\n]%*c", l[ln]);
// Check scanned number is as expected
if (n != 1)
break;
// Output result
printf("scanned %d string %d lines as: [- %s -]\r\n", n, ln, l[ln]);
// strlen(l) +2 to skip "\r\n" to point the next line head
p += strlen(l[ln++]) + 2;
} while (1);
n = sscanf(l[1], "%*[^0-9.]%s", ip);
printf("\r\n"
"parsed ip address as %s [n=%d] from [- %s -]\r\n",
ip, n, l[1]);
n = sscanf(l[2], "%[^://]%*c%*c%*c%[^:]%*c%d",
demo_url.protocol,
demo_url.ip,
&demo_url.port);
printf("\r\n"
"parsed %d url components as \r\n"
" protocol : %s\r\n"
" ip address : %s\r\n"
" port number : %d\r\n",
n,
demo_url.protocol,
demo_url.ip,
demo_url.port);
// Scan strings from l[3] with extra WHITESPACE characters
n = sscanf(l[3], "%s %s %s %s %s",
line_parts[0],
line_parts[1],
line_parts[2],
line_parts[3],
line_parts[4]);
printf("\r\n"
"parse %d parts from [- %s -] as [%s][%s][%s][%s][%s]\r\n",
n,
l[3],
line_parts[0],
line_parts[1],
line_parts[2],
line_parts[3],
line_parts[4]);
// Scan strings from l[4] without extra WHITESPACE characters
n = sscanf(l[4], "%s %s %s %s %s",
line_parts[0],
line_parts[1],
line_parts[2],
line_parts[3],
line_parts[4]);
printf("\r\n"
"parse %d parts from [- %s -] as [%s][%s][%s][%s][%s]\r\n",
n,
l[4],
line_parts[0],
line_parts[1],
line_parts[2],
line_parts[3],
line_parts[4]);
return 0;
}
代码的运行结果如下所列:
scanned 1 string 0 lines as: [- demo string -]
scanned 1 string 1 lines as: [- default via 192.168.0.1 dev eth0 -]
scanned 1 string 2 lines as: [- https://192.168.0.101:18883 -]
scanned 1 string 3 lines as: [- this is the
4th
line. -]
scanned 1 string 4 lines as: [- this is the 5th line. -]
parsed ip address as 192.168.0.1 [n=1] from [- default via 192.168.0.1 dev eth0 -]
parsed 3 url components as
protocol : https
ip address : 192.168.0.101
port number : 18883
parse 5 parts from [- this is the
4th
line. -] as [this][is][the][4th][line.]
parse 5 parts from [- this is the 5th line. -] as [this][is][the][5th][line.]
通过以上实验,对先前的几个困惑都找到了答案。
对sscanf的使用,总算有了些更清晰,更深入的理解。
本文参阅了:C语言中sscanf()函数的字符串格式化用法_aoxuely的博客-CSDN博客