【发布时间】:2016-01-17 13:58:03
【问题描述】:
我正在编写一个程序,我需要在其中搜索几个完整的数字。搜索部分似乎可以工作,但由于某种原因,程序跳过了几个单词。 我的代码如下:
#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;
}
提到的文件“numbers.txt”如下:
een
foo
drie
twee
acht
bla
zes
twaalf
elf
vier
程序输出:
een
drie
twee
acht
zes
vier
这意味着它正在跳过“twaalf”和“elf”。为什么会这样?我该如何解决?
感谢正手。
【问题讨论】:
-
这条语句
int count = sizeof(myFile)没有将count设置为myFile 的大小。它将count设置为指向FILE结构的指针的大小,通常在32 位系统上为4,在64 位系统上为8。因此,在声明for (int i = 0; i < count; ++i)中,您正在迭代数组的前 8 个元素。您应该将计数设置为sizeof(words)/sizeof(words[0])。