【发布时间】:2019-02-22 09:26:47
【问题描述】:
我是 C 编程的新手。我想从输入缓冲区字符串中提取值。我看到了sscanf 的几个示例,它适用于空格分隔符,但不适用于冒号或逗号。
我尝试在 sscanf 中使用一些正则表达式,但似乎仍然不起作用。
#include <stdio.h>
int main() {
char buffer[] = "T:192.164.7.1:22:user:pass:empty:test.txt";
char cmdChar;
char ipAddress[100];
int port;
char username[100];
char password[100];
char folder[100];
char fileName[100];
char fileExtension[100];
sscanf(buffer, "%1c:%[^:]%d:%s:%s:%s:%s.%s", cmdChar, ipAddress, &port, username, password, folder, fileName, fileExtension);
printf("%c \n\n", cmdChar);
}
尝试打印第一个字符cmdChar,但它返回为NULL。有人可以指出我做错了什么。谢谢!
【问题讨论】:
-
您需要将
&cmdChar传递给sscanf。 -
"%1c"相当没用,因为char无论如何都只是一个字符。限制对于防止缓冲区溢出的字符串更有意义。 -
[^:]%d将一直读取到:和:在字符串中省略,因此您的port将具有:ascii 值。