2015-03-02 71 views
2

我试图使用fscanf()在字符来读取必须以空格前面和后面:如何强制scanf匹配空格?

fscanf(input, "%*[ \t]%c%*[ \t]", output) 

但不幸的是,​​格式说明接受零个或多个匹配。无论如何,我可以要求它接受至少一场比赛,还是我需要使用类似getc()的东西?

+5

'fscanf'和空白不相处得非常好,所以IMO你用'fgetc'更好得到一次一个字符,或'fgets'同时获得线,然后自己进行解析。 – user3386109 2015-03-02 22:40:20

+0

'fscanf()'不适合正则表达式匹配。 – 2015-03-02 23:20:20

+0

类似'char sp1 [2],sp2 [2],输出; if(3 == fscanf(input,“%1 [\ t]%c%1 [\ t]”,sp1,&output,sp2))Good();'同意@ user3386109 – chux 2015-03-02 23:24:44

回答

1

可以用fscanf()解决这个帖子,但让我们看看fgetc()的方法。

// return 1 on success, else return 0 
int GetSpaceCharSpace(FILE *istream, int *ch) { 
    *ch = fgetc(istream); 
    if (!isspace(*ch)) 
    return 0; 

    // consume additional leading spaces as OP said "accept at least one match" 
    while (isspace(*ch = fgetc(istream))) 
    ; 
    // Code has a non-white-space 

    // Success if next char is a white-space 
    return isspace(fgetc(istream)); 
}