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

Why does my C++ char array terminate early?

本文关键字:终止 数组 字符 我的 c++ 为什么      更新时间:2023-10-16

下面的代码应该读取测试字符串,然后打开文件,在文本文件(包含多行)中通过读取前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] != '');
    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;
                }
            }
        }
    }
}

逻辑错误在以下代码块中:

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;
}

进一步检查代码,问题似乎在下面的代码块中。

     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++;
     }

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

你的索引逻辑是关闭的,所以你跳过索引8。这是特别有问题的,因为您是零初始化字符数组。这意味着数组中的任何空白都将被视为终止字符,字符数组的长度将显示为8。其他字符被读取并存储在数组中,但它们位于null字符之后。逻辑有点问题,所以据我所知,最后一个'f'没有被读取。

你的数组comparetest2String最终看起来像这样:

[1][2][3][4][5][f][6][7][][8][9][5]

那么当你输出它的时候,你得到:

12345f67

请注意,其他字符被读取并存储在数组中(减去最后一个'f'),但是字符串以''结束,因此不打印尾随字符。

你能试着从第三个if块的索引countTestChars中减去1吗?这有帮助吗?


基于std::string的溶液

如果你把它改成下面这样呢:

bool checkPrefix(const std::string& test, const std::string& input)
{
    const size_t PREFIX_LENGTH = 8;
    for (size_t i = 0; i < PREFIX_LENGTH; ++i)
    {
        if (input[i] != test[i])
        {
            return false;
        }
    }
    return true;
}
void test_value1()
{
    const std::string TEST_STRING = "12345f67895f";   
    std::cout << "Number of chars in test string" << TEST_STRING.length() << std::endl;
    std::ifstream testFile("test.txt");
    if (!testFile)
    {
        std::cout << "File not found " << std::endl;
        std::cout << "Press ENTER to EXIT " << std::endl;
        std::getchar();
        exit(0);
    }
    else
    {
        std::string line;
        while (getline(testFile, line))
        {
            if (checkPrefix(TEST_STRING, line))
            {
                std::cout << "Found " << line << std::endl;
            }
        }
    }
}

这适用于OP所述的多个输入行,并且不包含任何原始字符数组或容易出错的索引和计数器!

输入:

12345f67895f
BADPREFIX333
12345f67FDBC
输出:

12345f67895f
12345f67FDBC