gpt4 book ai didi

c - 我的程序没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:50 25 4
gpt4 key购买 nike

我需要找到一些字符串的位置。这些字符串存储在名为 queryfile 的文件中,来自另一个名为 datafile 的文件。

但是,我的程序没有按预期运行。有人可以帮助我吗?

我的程序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *queryfile;
queryfile = fopen("op2query.txt","r");

FILE *datafile;
datafile = fopen("op2data.txt","r" );

int i = 1;
char word[99];
char search[99];

if(queryfile==NULL) {
printf("Error in reading Query File");
exit(1);
}
if(datafile==NULL) {
printf("Error in reading Data File");
exit(1);
}

while(fscanf(queryfile,"%98s",search)==1){
while(fscanf(datafile,"%98s",word)==1){
if (strcmp(word,search)==0){
printf("\n %i %s ", i, search);
rewind(datafile);
i=1;
break;
}
else
i++;
}
}

fclose(datafile);
fclose(queryfile);
return 0;
}

最佳答案

我通过将查询字符串拆分为单词来构建每组要测试的单词的数组。这些词可以跨越数据文件中的换行符。我将数据文件位置标记在集合的第二个词上,如果搜索失败,我会寻找该点(如有必要)。即使我复制数据文件中的每个单词“age”,该程序也会成功。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXWORDS 5
#define MAXLEN 99

int main()
{
int j, i, done, words, count;
long mark;
char word[MAXLEN];
char search[MAXLEN];
char *tok, *sptr[MAXWORDS];
FILE *queryfile;
FILE *datafile;

if ((queryfile = fopen("op2query.txt","r")) == NULL) {
printf("Error in reading Query File");
exit(1);
}
if ((datafile = fopen("op2data.txt","r" )) == NULL) {
printf("Error in reading Data File");
exit(1);
}

while(fgets(search, MAXLEN, queryfile) != NULL){
words = 0;
done = 0;
count = 0;
mark = -1;
tok = strtok(search, " \r\n");
while (tok && words < MAXWORDS) { // build array of query
sptr[words++] = tok;
tok = strtok(NULL, " \r\n"); // strips newline too
}
if (words < 1) // no more queries
break;
rewind(datafile); // beginning of file

while (!done) { // until none to read
count++;
if (mark >= 0) // when more than one word to search
fseek (datafile, mark, SEEK_SET);
mark = -1;
for (j=0; j<words; j++) {
if (j == 1) // mark for next search
mark = ftell(datafile);
if (fscanf(datafile, "%98s", word) != 1){
done = 1; // end of file
break;
}
if (strcmp(sptr[j], word)!=0)
break; // failed multi word search
}
if (done)
printf("NOT FOUND!");
else if (j == words) { // if all words found
printf("%d", count);
done = 1; // success
}
}
for (i=0; i<words; i++)
printf(" %s", sptr[i]); // show array of words asked
printf("\n");
}
fclose(datafile);
fclose(queryfile);
return 0;
}

程序输出:

18 wisdom
40 season
NOT FOUND! summer
22 age of foolishness

更新 - 当查询未找到时,我打印NOT FOUND!。在查询文件中添加了“summer”。

关于c - 我的程序没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826834/

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