【发布时间】:2014-07-13 11:05:04
【问题描述】:
我有一个哈希表 ADT,它有两个函数,插入和查找。我在插入函数中输入了一个哈希表、哈希表大小、ID # 和书名,然后将其插入到哈希表中。当我将字符串文字传递给它时,这很好用,即insert(...,"Hello, world!"...); 当我从文件中读取字符串,将它们存储在数组中并尝试使用我的插入和查找函数时,它不起作用。
我的所有代码都在这里,但最重要的文件是 main.c 和 hash.c。 Hash.c 具有 newHash()、hash()、insert() 和 lookup() 函数,并且 main.c 从两个文件读取,在本例中为 test1.lib.in 和 test1.req.in,并从第一个file 将从每一行获取一本书的图书馆 ID 和标题,然后将其放入哈希表中。从第二个文件中,它获取书名请求,并应打印其链接列表中的 ID。
- 文件链接列表 https://docs.google.com/document/d/1tFNs-eVkfnCfjwAHcAUdHtUl1KVv_WcnW2IS0SRFvcM/edit?usp=sharing
有效的代码示例。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "list.h"
#include "hash.h"
int main(){
ListHndl* temp = newHash(10);
insert(442440, "cvyaqbznxel", 10,temp);
lookup(temp,"cvyaqbznxel", 10);
return 0;
}
无效的代码
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "list.h"
#include "hash.h"
int main(int argc, char * argv[]) {
if (argc != 3) {
printf("Incorrect arguments, please specify 2 files to be read\n");
return EXIT_FAILURE;
}
FILE *file = fopen( argv[1], "r");
FILE *secondFile = fopen(argv[2], "r");
if (file == 0 || secondFile == 0) {
printf("Could not open a file\n");
return EXIT_FAILURE;
}
int numDataLines2;
int numDataLines;
int hashTableSize;
//First line of first file gives number of lines in file and
//size of hash table to be made
if(fscanf(file, "%d%d", &numDataLines, &hashTableSize) < 2) {
printf("Unable to parse first line of first file\n");
return EXIT_FAILURE;
}
ListHndl* theHash = newHash(hashTableSize);
int libraryID;
char *tempString = calloc(numDataLines,41*sizeof(char));
char lineHolder[129];
//discard the new line which always shows up
fgets(lineHolder, 128, file);
for(int i = 0; i < numDataLines; i++) {
//Gets the whole line to be scanned with sscanf
fgets(lineHolder, 128, file);
//If the line consists of just a newline char, continue
if(strcmp(lineHolder, "\n") == 0 ) {
continue;
}
//Scans the line retrieved from fgets and placed in lineHolder
if(sscanf(lineHolder, "%d, %40[^\n]", &libraryID,&tempString[i]) == 0){
printf("Unable to parse line %d of first file\n",i+2);
return EXIT_FAILURE;
}
insert(libraryID, &tempString[i], hashTableSize, theHash);
}
char String[41];
fgets(String, 40, secondFile);
numDataLines2 = atoi(String);
char *storeSecondFileStuff = calloc(numDataLines2,41*sizeof(char));
for(int i = 0; i< numDataLines2; i++) {
fgets(lineHolder, 128, secondFile);
if(strcmp(lineHolder, "\n") == 0) {
continue;
}
if(sscanf(lineHolder, "%40[^\n]",&storeSecondFileStuff[i]) == 0) {
printf("Unable to parse line %d of second file\n",i+2);
return EXIT_FAILURE;
}
lookup(theHash, &storeSecondFileStuff[i], hashTableSize);
}
printf("\n");
fclose(file);
fclose(secondFile);
return 0;
}
谢谢!
【问题讨论】:
-
如果您不尝试讲述有关您的代码的故事,而是实际向我们展示,这对我们所有人来说会容易得多
-
我放了一个包含我所有代码的链接。需要我详细说明一下吗?
-
另外:sscce.org
-
我编辑了一些代码,它无法编译,因为它需要各种文件,感觉太多,无法粘贴到这里,但我认为程序的要点就在那里。