2011-04-08 49 views
0

我正在尝试使用'#'符号作为唯一分隔符来读取格式为#string 1 ## string 2 ## ....等的文件。我也试图将每个字符串复制到一个char数组中。这里有一点我当前的代码,但它似乎并不奏效:使用[^ ...]更正fscanf格式化输入的格式?

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

FP被打开,并且宣称,这语句总是出现假(不成功扫描)。

的思考?

+0

它是否与良好的欧盟scanf(或stdin文件)工作? – 2011-04-08 09:03:42

+1

我刚刚注意到你传递了1作为参数的等式比较的结果。这是一个错字,还是你的实际代码? – 2011-04-08 09:13:11

+0

您需要绕过输入中的“#”。 – pmg 2011-04-08 09:28:18

回答

1

我想你可能需要:

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

这样做有些不同... – dreamlax 2011-04-08 09:13:21

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; 
}