2

是否可以仅在 C 中扫描带有空格 + 单词的文本?

这是示例文本:

"Oh my   god!"

这是功能:

...declarations...malloc...etc.
for (int i = 0; ; i++)
{
    some_scanf_func(s, "%some format", input);
    c = getchar();
    if (c == EOF)
        break;
    else
        ungetc(c, stdin);
}

所以我的输入是:

"Oh" when i = 0;

" my" when i = 1;

"   god!" when i = 2;

空格在单词的前面。标点符号被视为有效字符。

谢谢你 chux 的伎俩,也谢谢查理的回答。

4

3 回答 3

2

使用"%*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;
}
于 2013-11-02T16:50:26.160 回答
2

另一种方法是:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int foo(char *s, char **result, int size) {
        char *p1 = s;
        int count = 0;
        while(*p1 && count < size-1) {
                char *p2 = p1;
                for( ; *p2 && isspace(*p2); p2++);
                if(*p2) {
                        for( ; *p2 && isspace(*p2) == 0; p2++);
                        result[count++] = strndup(p1, p2 - p1);
                }
                p1 = p2;
        }
        result[i] = 0;
        return count;
}

int main(void) {
        char *result[100];
        int n = foo("  Oh my   god! ", result, 100);
        for(int i = 0; i != n; i++) {
                printf("%d '%s'\n", i, result[i]);
                free(result[i]);
        }
        return 0;
}

我想有点丑陋。但它打印

0 '  Oh'
1 ' my'
2 '   god!'

并且对原始输入也做了正确的事情。

于 2013-11-02T17:02:28.187 回答
1

将其读入字符串 - 然后解析它。

在检测是否有空格后,您可以使用 sscanf() 解析与 scanf 相同的字符串

于 2013-11-02T16:38:49.933 回答