gpt4 book ai didi

c++ - 为什么我的 C++ 字符数组提前终止?

转载 作者:行者123 更新时间:2023-11-30 02:37:06 26 4
gpt4 key购买 nike

下面的代码应该读取测试字符串然后打开文件并通过读取前 8 个字符在文本文件(包含多行)中找到相似的字符串以确保代码在正确的行上然后读取接下来的 4 个可能不同的字符每次。

代码对前 8 个字符工作正常,但它从不读取最后 4 个字符

void test_value2()
{
char charRead;
unsigned char test2String[65] = "12345f67895f";
unsigned char comparetest2String[65] = { 0 };
unsigned int counter1 = 0, countChars = 0, countTestChars = 0, countChars2 = 0;
std::fstream testResultsFile;
testResultsFile.open("C:\\Tan\\test.txt", ios::in);
do
{
counter1++; //count number of chars in test2String
} while (test2String[counter1] != '\0');
cout << "number of chars in test2String " << counter1 << endl;

if (!testResultsFile)
{
cout << "File not found " << endl;
cout << "Press ENTER to EXIT " << endl;
getchar();
exit(0);
}
else
{
while (!testResultsFile.eof())
{
testResultsFile.get(charRead); // Read char from the file
countChars++; // count total character read for future comparison with countTestChars
if (countTestChars == 8)
{
countChars2 = countChars;
countTestChars++;
}
if ((charRead == test2String[countTestChars]) && (countTestChars < 9))
{
comparetest2String[countTestChars] = charRead;
countTestChars++;
}
if ((countTestChars > 8) && (countTestChars < counter1)) // if at least first 8 chars matched, keep reading string
{
cout << "trying to read again" << endl;
comparetest2String[countTestChars] = charRead;
countTestChars++;
if (countTestChars == counter1)
{
cout << "done " << endl;
cout << comparetest2String << endl;
break;
}
}
}
}
}

最佳答案

逻辑错误在以下 block :

if (countTestChars == counter1)
{
cout << "done " << endl;
cout << comparetest2String << endl;

// This line here causes the code to break
// out of the while loop after 8 characters are read.
break;
}

更新

进一步检查代码,问题似乎出在以下 block 中。

     if (countTestChars == 8)
{
countChars2 = countChars;

// This line is the culprit. You end up skipping an index.
// Since comparetest2String is zero initialized, you don't
// rest of comparetest2String when you print it.
countTestChars++;
}

删除上面的行可以解决问题。

请参阅 http://ideone.com/b6ebWu 处的工作代码.

关于c++ - 为什么我的 C++ 字符数组提前终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32031036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com