Dan*_*ore 2 c++ arrays compare char
您好,这是我的代码段,我正在尝试实现Morris-Pratt算法.当我比较我的变量时,如果发现它们不匹配,这是因为我的一个变量"Temp"正在将额外的字符添加到数组的末尾.这是我的代码......
// Calculate the next talbe
char test[searchLen];
for(int i = 0; i < searchLen; i++)
{
test[i] = fileContent[currPos+i];
}
cout << "SEARCHLEN: " << searchLen << endl;
cout << "TEST: " << '\t' << '\t' << test << endl;
cout << "SEARCH: " << '\t' << search << endl;
cout << strcmp(test,search) << endl << endl;
// Determine if a match is detected
if(strcmp(test,search)==0)
{
cout << "----------------------> Match detected at: " << currPos << endl;
}
currPos ++;
}
return numberOfComparisons;
}
Run Code Online (Sandbox Code Playgroud)
输出看起来像这样......
SEARCHLEN: 8
TEST: athsoutg5?h
SEARCH: brilling
-1
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样5?H不应该在那里而且会破坏我的代码.
您需要添加一个空终止符.
char test[searchLen + 1];
test[searchLen] = '\0';
Run Code Online (Sandbox Code Playgroud)