使用[^ ...]格式化fscanf格式化输入的格式?

时间:2011-04-08 09:00:07

标签: c scanf

我正在尝试使用#string 1 ## string 2 ## ....等格式读取文件,使用'#'符号作为唯一分隔符。我还试图将每个字符串复制到一个char数组中。这是我当前的一些代码,但它似乎不起作用:

char temp[20];
if(fscanf(fp, "%15[^#]", temp ==1) ....

打开并声明了fp,并且此语句始终显示为false(扫描失败)。

思想?

2 个答案:

答案 0 :(得分:1)

我想你可能需要:

if(fscanf(fp, "#%15[^#]#", temp) ==1)

答案 1 :(得分:1)

我写了little working example。随意更改它以满足您的需求:)

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

int main(void) {
  char input[] = "#string 1##string two##three##last but one##five#";
  char tmp[100];
  char *pinput = input;
  /* the conversion specification is
  **                      %99[^#]
  ** the other '#' are literals that must be matched */
  while (sscanf(pinput, "#%99[^#]#", tmp) == 1) {
    printf("got [%s]\n", tmp);
    pinput += strlen(tmp) + 2;
  }
  return 0;
}