我正在写一个程序,我需要搜索几个完整的数字.搜索部分似乎有效但由于某种原因,该程序正在跳过几个单词.我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[]){
char temp[128];
char *words[] = {"een","twee","drie","vier","vijf","zes","zeven","acht",
"negen","tien","elf","twaalf","dertien","veertien",
"vijftien","zestien","zeventien","achttien",
"negentien","twintig"};
//Open the file
FILE *myFile;
myFile = fopen("numbers.txt","r");
int count = sizeof(myFile);
if (myFile == NULL){
printf("File not found\n");
}
else {
//Search the words
while(!feof(myFile)){
//Get the words
fgets(temp, sizeof(temp), myFile);
for (int i = 0; i < count; ++i){
if((strstr(temp, words[i])) != NULL) {
printf("%s\n", temp);
}
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
提到的文件"numbers.txt"如下:
een
foo
drie
twee
acht
bla
zes
twaalf
elf
vier
Run Code Online (Sandbox Code Playgroud)
节目输出:
een
drie
twee
acht
zes
vier
Run Code Online (Sandbox Code Playgroud)
这意味着它正在跳过"twaalf"和"elf".为什么,我该如何解决这个问题?
感谢正手.
int count = sizeof(myFile);
Run Code Online (Sandbox Code Playgroud)
这似乎是一个错字或误解.sizeof(myFile)计算指针使用的字节数.你需要使用:
int count = sizeof(words)/sizeof(words[0]);
Run Code Online (Sandbox Code Playgroud)
值count将是之后的单词数.