对于一个项目,我试图从一个字符串中读取一个 int 和一个字符串。这里唯一的问题是 sscanf 在看到空格和一些特殊字符时似乎中断了对 %s
的读取。我只想打印特殊字符中存在的字符串。无论如何要绕过这个限制?这是我正在尝试做的一个例子:
类似于this link变化不大
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char** argv) {
int age;
char* buffer;
buffer = malloc(200 * sizeof(char));
sscanf("19 cool kid >>> ram <<<", "%d %[^\t\n] >>> %*s <<<", &age, buffer);
printf("%s is %d years old\n", buffer, age);
return 0;
}
它打印的是:"cool kid >>> ram <<< is 19 years old" 我需要"ram is 19 years old"。有什么解决办法吗?
注意:有时“cool kid”字符串也会像这样出现“coolkid”。
最佳答案
你有它,你只是把你的弃牌放在了错误的地方(还有一个小的大写问题):
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int age;
char* buffer;
if (!(buffer = malloc(200 * sizeof *buffer))) {
fprintf (stderr, "error: virtual memory exhausted.\n");
return 1;
}
sscanf("19 cool kid >>> ram <<<", "%d %*[^>] >>> %s <<<", &age, buffer);
printf("%s is %d years old\n", buffer, age);
free (buffer);
return 0;
}
输出
$ ./bin/sscanf_strange
ram is 19 years old
关于c - 使用 sscanf 读取带有空格和特殊字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32217182/