2013-05-28 50 views
0

我在這個程序的輸出中遇到了一些麻煩。我需要在一行上打印動詞,如果沒有動詞,我需要打印一個單獨的語句。例如。在C中使用printf格式化二進制搜索的輸出?

"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; 
} 

任何想法?

+1

如何使用二分查找搜索字符串中的單詞?二進制搜索需要對字段進行排序。 – Dipto

+1

而不是打印'printf(「動詞是:%s \ n」,動詞[position]);',將'verbs [position]'存儲到數組中並在循環後打印。 – Dipto

回答

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; 

像否則檢查總是在循環設置1。

如果你不想重複「的動詞有:」,添加一個檢查爲

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

    } 
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; 
} 
0

如果你更感興趣的只是具有搜索完成,而不是實施它自己(即假設「執行搜索」不是你的實際任務),你應該使用標準庫的鮮爲人知的英雄bsearch()

請注意,這需要輸入數據(您正在搜索的數組)進行排序,但您似乎是因爲您已經在進行二分查找。