你好,这是我的一段代码,我正在尝试实现 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;
}
输出看起来像这样......
SEARCHLEN: 8
TEST: athsoutg5?h
SEARCH: brilling
-1
如您所见,5?H 不应该存在并且破坏了我的代码。
最佳答案
您需要添加一个空终止符。
char test[searchLen + 1];
test[searchLen] = '\0';
关于c++ - 字符数组输出额外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739920/