【问题标题】:Program is not searching entire file程序没有搜索整个文件
【发布时间】: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 &lt; count; ++i) 中,您正在迭代数组的前 8 个元素。您应该将计数设置为sizeof(words)/sizeof(words[0])

标签: c file search


【解决方案1】:
int count = sizeof(myFile);

这似乎是一个错字或误解。 sizeof(myFile) 计算为指针使用的字节数。你需要使用:

int count = sizeof(words)/sizeof(words[0]);

count 的值将是之后的单词数。

【讨论】:

  • 但是为什么他的语言名称中会出现数字 1 到 8?那么他必须有 8 个字节的指针,因此使用 x64?
  • @TobiasKnauss,这是正确的。
【解决方案2】:

您使用 counti 错误。
该文件有 10 行,您将 count 设置为此数字 10,然后使用它来访问您的数字数组。您需要将 count 设置为数组中的元素数。

【讨论】:

  • “你将 count 设置为这个数字 10” :不,sizeof 给出可变大小,而不是文件中的行数或字节数或其他任何内容。
  • 好的,但是sizeof(myfile) 是错误的部分。您不需要文件的大小,而是数组中元素的数量!我以为你会明白的。
  • 当然,但是你写了“你将count设置为这个数字10”这显然是错误的,这意味着你不明白sizeof是如何工作的。
  • 不,我现在不知道,因为我最近几年一直在使用 c#,我不需要 sizeof。我必须回想很久才能记住纯 C++。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多