c++ - 字符数组输出额外的字符

标签 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 不应该存在并且破坏了我的代码。

最佳答案

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

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

关于c++ - 字符数组输出额外的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739920/

相关文章:

rust - 有没有比将其转换为字符串更好的方法来测试字符是否为空白?

iphone - 如何将 NSData 转换为 Char?

java - 一次读入文本文件 1 行并将单词拆分为 Array Java

c++ - 构造函数初始化数组

c++ - 在 windows nts 模式下构建 php 扩展

C++ 参数传递数组与单个项

javascript - Firebase - 对象与数组并返回 .key()

c - 为什么这个循环在 c 中运行无限次?

c++ - 移除模板参数包的最后一个类型

c++ - boost::signals2 仍然向引用死亡的对象发出信号