Char数组输出额外的字符

时间:2012-05-24 14:51:43

标签: c++ arrays char compare

你好这是我的代码片段,我试图实现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不应该在那里而且会破坏我的代码。

2 个答案:

答案 0 :(得分:6)

您需要添加一个空终止符。

   char test[searchLen + 1];
   test[searchLen] = '\0';

答案 1 :(得分:1)

看起来你的字符串没有以\ 0结尾,也许你忘记复制它/把它放在那里?