0

我在这个程序的输出上遇到了一些问题。我需要将动词打印在一行上,如果没有动词,我需要打印单独的语句。例如。

"talk and walk"应该打印"The verbs are: talk walk"

"hello there"应该打印"There are no verbs"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int binary_search(char *list_of_words[], int size, char *target){
    int bottom= 0;
    int mid;
    int top = size - 1;
    int found = 0;

    while(bottom <= top && !found){
        mid = (bottom + top)/2;
        if (strcmp(list_of_words[mid], target) == 0){
            //printf("%s found at location %d.\n", target, mid+1);
            found = 1;
        } else if (strcmp(list_of_words[mid], target) > 0){
            top    = mid - 1;
        } else if (strcmp(list_of_words[mid], target) < 0){
            bottom = mid + 1;
        }
    }
    if (found == 1)
        return mid;
    else
        return -1;
}

int main(int argc, char* argv[]){
    char *input = strtok(argv[1], " \"\n");
    char *verbs[5] = { "do", "make", "take", "talk", "walk" };
    int position;
    int check = 0;
    while (input != NULL) {
        //printf("%s\n", input);
        position = binary_search(verbs, 5, input);
        if (position != -1)
            printf("The verbs are: %s\n", verbs[position]);
            check = 1;
        input = strtok(NULL, " ");
    }
    if (check == 0){
        printf("There are no verbs\n");
    }
    return 0;
}

有任何想法吗?

4

3 回答 3

4

它似乎工作正常,但您需要在周围添加括号

    if (position != -1)
        printf("The verbs are: %s\n", verbs[position]);
        check = 1;

    if (position != -1) {
        printf("The verbs are: %s\n", verbs[position]);
        check = 1;
    }

否则 check 在循环中始终设置为 1。

如果您不想重复 "The verbs are:" ,请添加一个检查

    if (position != -1) {
        if (first) {
            printf("The verbs are:");
            first = 0;
            check = 1;
        }
        printf(" %s", verbs[position]);

    }
于 2013-05-28T10:33:31.237 回答
1
int main(int argc, char* argv[]){
    char *input = strtok(argv[1], " \"\n");
    char *verbs[5] = { "do", "make", "take", "talk", "walk" };
    char match[5] = {0};
    int position;
    int check = 0;
    while (input != NULL) {
        //printf("%s\n", input);
        position = binary_search(verbs, 5, input);
        if (position != -1){
            //printf("The verbs are: %s\n", verbs[position]);
            match[position]=1;//match[position] = check = 1;
            check = 1;
        }
        input = strtok(NULL, " ");
    }
    if (check == 0){
        printf("There are no verbs\n");
    } else {
        int i;
        printf("The verbs are: ");
        for(i=0;i<5;++i)
            if(match[i])
                printf("%s ", verbs[i]);
        printf("\n");
    }
    return 0;
}
于 2013-05-28T10:33:53.013 回答
0

如果您对完成搜索而不是自己实现它更感兴趣(即,假设“实现搜索”不是您的实际任务),您应该使用标准库中鲜为人知的英雄,bsearch().

请注意,这需要对输入数据(您正在搜索的数组)进行排序,但您的数据似乎是因为您已经在进行二进制搜索。

于 2013-05-28T12:22:54.550 回答