使用 fscanf 时,我可以将非字母字符设置为 c 中的定界符吗?

Can I set non-alphabetic characters as a delimeter in c when using fscanf?

我正在尝试使用

从文件中读取字符串
while(fscanf(fd, "%s ", word) != EOF) {}

其中 fd 是文件,word 是我存储字符串的位置。 但是,这有效地使用了空格作为分隔符。目前,如果我有一个读取 "this% is, the4 str%ng" 的文件,它将导致字符串 "this%"、"is,"、"the4" 和 "str%ng"。我需要它是 "this" "is" "the" "str" "ng"。是否可以使用 fscanf 执行此操作,或者我还需要使用其他东西吗?

我看到了一些答案 here and here,但它们似乎对我没有帮助。

这些答案显示了 "%[] 格式说明符的使用。作为一个例子,假设你有这个从控制台得到两个字符串:

#include <stdio.h>

int main(void){
    char s1[100] = "", s2[100] = "";
    int res;

    res = scanf("%99[^%]%%%99[^%]%%", s1, s2);
    printf("%d %s %s\n", res, s1, s2);
}

第一个 % 开始每个格式规范,^% 告诉 scanf% 停止,然后下一个 "escaped" 双 % 告诉 scanf 读取停止扫描的 %。然后它重复第二个字符串,因此一个字符串的格式规范是 %99[^%]%% .

为了让格式看起来更简单,假设分隔符不是%而是#,那么代码就是:

#include <stdio.h>

int main(void){
    char s1[100] = "", s2[100] = "";
    int res;

    res = scanf("%99[^#]#%99[^#]#", s1, s2);
    printf("%d %s %s\n", res, s1, s2);
}

函数fscanf类似。


编辑

这个答案不处理 "unknown" 分隔符,所以我修改了代码。

#include <stdio.h>

int main(void){
    char s1[100] = "";
    while(scanf("%99[^!£$%&*()_-+={};:'@#~,.<>/?0123456789]", s1) == 1) {
        getchar();                      // remove the delimiter
        printf("%s\n", s1);
    }
}

请注意,我没有包含字符 ^"[] 作为分隔符。

如果您没有特定的分隔符(这似乎是您的情况),您需要手动解析每个文件行。您可以使用 fgets() 读取每一行,然后手动解析(例如忽略每个 non-alphabetic 个字符)。

此致