2013-02-21 52 views
0

我正在使用C++實現simple_search_text。該程序運行良好的大多數輸入,但是當我使兩個strings相同時,輸出顯示任何內容並正常返回。這可能是一個錯誤,但我無法找到它。我試着遵循算法的控制流程,但仍然沒有成功。我已經在下面給出了實施。simple_search_text的實現

#include<iostream> 
#include<cstring> 
using namespace std; 
int simple_text_search(const char* p, const char* q); 
int main(){ 
    if(int i = simple_text_search("ell", "ell")) //strings are not from standard input 
     cout << "Found at " << i; 
    return 0; 
} 

int simple_text_search(const char* p, const char* q){ 
    int m = strlen(p); 
    int n = strlen(q); 
    int i = 0; 
    while(i + m <= n) { 
     int j = 0; 
     while(q[i + j] == p[j]){ 
      j = j + 1; 
      if(j == m) 
       return i; 
     } 
     i = i + 1; 
    } 
    return -1; 
} 

回答

3

您的函數返回0作爲答案。 if語句讀取爲false,因此不輸出答案。這是因爲,語句a=b的值是分配後變量a的值。

View fixed version here - 檢查顯式返回值是否爲-1

修復 -

if((i= simple_text_search("ell", "ell")) !=-1) 
             ^^^^^^^ 
+0

它打印:'在1'用於上述'input'實測值。 – 2013-02-21 05:11:56

+0

請看鏈接,'找到0' – 2013-02-21 05:13:09

+0

是的'主'部分有一個小錯誤。謝謝。 – 2013-02-21 05:15:17