0

我正在使用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语句将其读取为错误,因此不输出答案。这是因为,语句a=b的值就是赋值后变量的值a

在此处查看固定版本- 检查返回值是否-1明确。

使固定 -

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