【发布时间】:2016-08-03 00:42:18
【问题描述】:
我目前正在完成这项任务,但我被困住了。目标是读取文件并查找文件中的字符串中是否存在这些 char 值。我必须将文件中的字符串与作为参数输入的另一个字符串进行比较。但是,只要每个 char 值都在文件中的字符串中,它就会“匹配”。
示例(输入和输出):
./a.out file1 完成
完成是在白痴中
done 不在小狗中
示例(文件 1):
白痴
小狗
如您所见,比较字符串的顺序无关紧要,文件也遵循每行一个单词。我已经编写了一个程序来查找另一个字符串中是否存在 char 值,但这只是问题的一部分。知道该怎么做吗?
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
FILE *f = fopen(argv[1], "r");
char *line = NULL;
size_t len = 0;
ssize_t read;
char *word = argv[2];
if(argc != 3){
printf("./a.out <file> <word>\n");
exit(EXIT_SUCCESS);
}
if(f == NULL){
printf("file empty\n");
exit(EXIT_SUCCESS);
}
// confused what this loop does too
while((read = getline(&line, &len, f)) != -1){
char *c = line;
while(*c){
if(strchr(word, *c))
printf("can't spell \"%s\" without \"%s\"!\n", line, word);
else
printf("no \"%s\" in \"%s\".\n", word, line);
c++;
}
}
fclose(f);
exit(EXIT_SUCCESS);
}
【问题讨论】:
-
看起来我得到了一些意见但没有回应,我的问题措辞很糟糕吗?如果需要,我可以改写或解释。
-
任务是检查字符,而不是字符串。因此,根据您所写的要求,字符顺序无关紧要(老师可能会给出不同的指示)。
-
只是令人困惑。在这里,您正在测试您的文件中的字符是否在您的输入中。
-
只有一个变量
all_found设置为真值;如果strchr返回NULL,则将all_found设置为false 值并中断。 -
啊,你应该
char *c = word;和strchr(line, *c);您正在检查命令行中单词中的所有字符是否存在于给定行中。
标签: c string file char substring