我正在尝试创建一个带有输入字符串的程序(作为命令行参数),然后打印出字符串中的动词。动词列表位于单独的头文件中的数组中。该程序目前正在查找动词,但它多次打印相同的单词。这是我的代码:
#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;
}
有什么想法吗?
答案 0 :(得分:1)
好的,你发布的代码有各种不正确的东西。
无论如何,我根据你的问题修改了你的程序,以及它的措辞(如果你只想要一个或多个输入字符串,我有点不清楚,我假设1)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DELIM ",.-+=*"
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);
return;
} else if (strcmp(list_of_words[mid], target) > 0){
top = mid - 1;
} else if (strcmp(list_of_words[mid], target) < 0){
bottom = mid + 1;
}
}
}
int main(int argc, char* argv[]){
int i = 1;
char *input = strtok(argv[1], DELIM);
char *verbs[5] = { "do", "make", "shit", "talk", "walk" };
while (input != NULL) {
printf("looking at %s\n", input);
binary_search(verbs, 5, input);
input = strtok(NULL, DELIM);
}
return 0;
}
如果你期望通过argv改变几个字符串:
while (input != NULL) {
printf("looking at %s\n", input);
binary_search(verbs, 5, input);
input = strtok(NULL, DELIM);
}
到
for (i = 1; i < argc - 1; i++) {
input = strtok(argv[i], DELIM);
while (input != NULL) {
printf("looking at %s\n", input);
binary_search(verbs, 5, input);
input = strtok(NULL, DELIM);
}
}
希望这有帮助。