使用"%*s%n"
.
%*s
跳过前导空白,然后扫描非空白文本。*
说不说结果。
%n
说记录扫描的位置(如果我们到达那里)。
char input[100];
char *p = input;
int count = 0;
if (fgets(input, sizeof input, stdin) == NULL) {
; // handle EOF
}
while (*p) {
int n = 0;
sscanf(p, "%*s%n", &n);
if (n == 0) break;
p = &p[n];
count++;
}
用buffer
char *previousp;
while (*p) {
int n = 0;
sscanf(p, "%*s%n", &n);
if (n == 0) break;
previousp = p
p = &p[n];
// At this point `previousp` to p is OP desired output.
printf(%.*s\n", p - previousp, previousp);
count++;
}
OP 想要使用sscanf()
但只是按照@Charlie Burns 的建议沿着缓冲区前进是有道理的。
const char *p = buffer;
while (*p) {
const char *endp = p;
while (isspace(*endp)) endp++;
while (*endp && !isspace(*endp)) endp++;
// At this point `p` to `endp` is OP desired output.
printf(%.*s\n", endp - p, p);
p = endp;
}