gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:49:02 26 4
gpt4 key购买 nike

我正在尝试使用以下命令从文件中读取字符串

while(fscanf(fd, "%s ", word) != EOF) {}

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

我看到了一些答案 herehere但他们似乎并没有帮助我。

最佳答案

这些答案显示了 "%[] 格式说明符的使用。举个例子,假设您使用它从控制台获取两个字符串:

#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% 处停止,下一个“转义”双 % 告诉 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类似。


编辑

这个答案不处理“未知”分隔符,所以我修改了代码。

#include <stdio.h>

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

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

关于使用 fscanf 时,我可以将非字母字符设置为 c 中的定界符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com