如果我们不知道字符串的大小并且不能动态分配内存,有没有办法用 sscanf 标记字符串?
Is there a way to tokenize a string with sscanf if we don't know the size of the string and can't dynamically allocate memory?
如果我们不知道字符串的大小并且不能动态分配内存,有没有办法用 sscanf 对字符串进行标记?
这是一个不满足上述要求的例子:
char token[100];///we can't do that in this case since we don't know the size of the string
int offset = 0;
int consumed = 0;
sscanf(format + offset, "%s%n", tokenf, &consumed);
offset += consumed;
注意:我知道 strtok
、strtok_r
和 strtok_s
,但我问的是 sscanf
或其他方式。
此外,strtok
函数是否为令牌动态分配内存?
如果您使用的是 GNU libc(或最近的 POSIX 版本),您可以使用 m
修饰符来为 scanf 分配内存:
char *token;
int offset = 0;
int consumed = 0;
if (sscanf(format + offset "%ms%n", &token, &consumed) >= 1) {
offset += consumed;
... do something with token ...
free(token);
}
但是,这是一个 GNU 扩展(也是 POSIX-2008 的一部分,因此至少在某种程度上可以移植),因此可能无法在任何地方使用。另外,一定要检查 sscanf
...
中的 return 值
如果我们不知道字符串的大小并且不能动态分配内存,有没有办法用 sscanf 对字符串进行标记?
这是一个不满足上述要求的例子:
char token[100];///we can't do that in this case since we don't know the size of the string
int offset = 0;
int consumed = 0;
sscanf(format + offset, "%s%n", tokenf, &consumed);
offset += consumed;
注意:我知道 strtok
、strtok_r
和 strtok_s
,但我问的是 sscanf
或其他方式。
此外,strtok
函数是否为令牌动态分配内存?
如果您使用的是 GNU libc(或最近的 POSIX 版本),您可以使用 m
修饰符来为 scanf 分配内存:
char *token;
int offset = 0;
int consumed = 0;
if (sscanf(format + offset "%ms%n", &token, &consumed) >= 1) {
offset += consumed;
... do something with token ...
free(token);
}
但是,这是一个 GNU 扩展(也是 POSIX-2008 的一部分,因此至少在某种程度上可以移植),因此可能无法在任何地方使用。另外,一定要检查 sscanf
...