C ++字符串子句超出范围问题

时间:2018-07-03 10:35:26

标签: c++

我是一名正在学习C ++的学生,并且我尝试创建的代码有问题。我应该创建的代码旨在查找用户将输入的2个单词的汉明距离。 (例如,“铁人”和“铁”的汉明距离为“ 3”)

但是,当我尝试编译时遇到了一个错误,我似乎无法找出问题所在。如果第一个输入比第二个输入长,则会弹出“字符串下标超出范围”的错误。(仅当我尝试输入“ Spiderman Ironman”时,此错误才起作用。较短的单词,例如“ Sean Sea”可以正常工作。)如果第二个输入比第一个输入长,或者如果两个输入的长度相同,则整个代码可以正常工作。

string str1;
string str2;

cout << "Question 1" << endl;
cout << "Input two words (separated by space or enter) : ";

cin >> str1;
cin >> str2;

int count = hamming_distance(str1, str2);

cout << "> Hamming distance between \"" << str1 << "\" and \"" << str2 << "\" is " << count << endl;



int i;
int firstLength = str1.length();
int secondLength = str1.length();
int thirdLength;
int counter = 0;

//if the longest word is first string (Where the issue is causing)
if (firstLength > secondLength)
{
    thirdLength = firstLength - secondLength;
    for (i = 0; i < firstLength; i++)
    {
        if (str1[i] != str2[i])
        {
            counter++;
        }
    }
    for (i = 0; i < thirdLength; i++)
    {
        counter++;
    }
}

//if the longest word is second string
else if (secondLength > firstLength)
{
    thirdLength = secondLength - firstLength;
    for (i = 0; i < secondLength; i++)
    {
        if (str1[i] != str2[i])
        {
            counter++;
        }
    }
    for (i = 0; i < thirdLength; i++)
    {
        counter++;
    }
}

//if both words have the same length
else if (firstLength == secondLength)
{
    for (i = 0; i < firstLength; i++)
    {
        if (str1[i] != str2[i])
        {
            counter++;
        }
    }
}

return counter;

如果大家都能帮助我找出我的代码的实际问题,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要正确初始化变量:

int firstLength = str1.length();
int secondLength = str2.length();

您还要确定一个字符串大于另一个字符串,然后根据较长字符串的长度继续访问较短字符串中的元素,这会给您下标超出范围的错误。当firstLength> secondLength时,您需要修改测试,反之亦然。