0

を使用して simple_search_text を実装していC++ます。プログラムはほとんどの入力に対して正常に実行されますが、両方をstrings同じにすると、出力は何も表示されず、正常に戻ります。これはバグかもしれませんが、見つけることができません。アルゴリズムの制御フローに従ってみましたが、まだ成功していません。以下に実装を示しました。

#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;
}
4

1 に答える 1

3

関数は答えとして 0 を返します。ステートメントはifそれを false として読み取るため、答えを出力しません。これは、ステートメントa=bの値が代入後の変数の値であるためですa

ここで修正版を表示- 戻り値が-1明示的かどうかを確認します。

修理 -

if( (i= simple_text_search("ell", "ell")) !=-1)  
                                        ^^^^^^^
于 2013-02-21T05:07:01.330 に答える