超出范围的C++字符串子脚本 我是一个正在学习C++的学生,我有一个问题,我试图创建一个代码。我应该创建的代码是为了找到用户将输入的两个单词的汉明距离。例如,铁人和铁人的汉明距离为3
然而,我在尝试编译时遇到了一个错误,我似乎无法找出问题所在。如果第一次输入的长度大于第二次输入的长度,字符串下标超出范围的错误会不断出现。只有当我尝试输入蜘蛛侠铁人时,它才失败。肖恩·海(Sean Sea)这样的短词很好用。如果第二个输入比第一个输入长,或者两个输入长度相同,则整个代码工作正常超出范围的C++字符串子脚本 我是一个正在学习C++的学生,我有一个问题,我试图创建一个代码。我应该创建的代码是为了找到用户将输入的两个单词的汉明距离。例如,铁人和铁人的汉明距离为3,c++,C++,然而,我在尝试编译时遇到了一个错误,我似乎无法找出问题所在。如果第一次输入的长度大于第二次输入的长度,字符串下标超出范围的错误会不断出现。只有当我尝试输入蜘蛛侠铁人时,它才失败。肖恩·海(Sean Sea)这样的短词很好用。如果第二个输入比第一个输入长,或者两个输入长度相同,则整个代码工作正常 string str1; string str2; cout << "Question 1" << endl; cout << "Input two words (s
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;
如果你们能帮我找出代码的实际问题,我将不胜感激。谢谢大家! 您需要正确初始化变量:
int firstLength = str1.length();
int secondLength = str2.length();
您还可以确定一个字符串比另一个字符串大,然后根据长字符串的长度继续访问短字符串中的元素,这会导致下标超出范围错误。当firstLength>secondLength时,您需要修改测试,反之亦然。您正在将firstLength和secondLength初始化为str1.length如果您对int i=0进行第一次循环;i