【发布时间】:2013-05-28 14:30:50
【问题描述】:
我正在尝试制作一个程序,该程序接受输入的字符串(作为命令行参数),然后打印出字符串中的动词。动词列表位于单独的头文件中的数组中。该程序当前正在查找动词,但它多次打印相同的单词。这是我的代码:
#include "verbs.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void binary_search(char *list_of_words, int size, char *target){
int bottom= 0;
int mid;
int top = size - 1;
while(bottom <= top){
mid = (bottom + top)/2;
if (strcmp(&list_of_words[mid], target) == 0){
printf("%s found at location %d.\n", target, mid+1);
break;
}
if (strcmp(&list_of_words[mid], target) == 1){
top= mid - 1;
}
if (strcmp(&list_of_words[mid], target) == -1){
bottom= mid + 1;
}
}
}
int main(int argc, char* argv[]){
char *input;
int i = 0;
input = strtok (argv[1], " \"\n");
while (input != NULL){
for (i = 0; i < VERBS; i++){ //VERBS is defined in verbs.h as 637
binary_search(verbs[i], VERBS, input);
}
input = strtok (NULL, " ");
}
return 0;
}
有什么想法吗?
【问题讨论】:
-
抱歉,这是作业吗?这里已经有一个类似的问题(仅在几个小时前发布)stackoverflow.com/questions/16781105/…
标签: c binary-search