通过函数读取文件时出现问题

Issue While Reading Files Through Function

本文关键字:问题 文件 函数 读取      更新时间:2023-10-16

我正试图为Caesar密码编写一个程序,现在我正在处理这个函数,以找到转换密码的密钥。

现在出现的问题是,当它读取文件时,程序中断,我得到错误:

"在ConsoleApplication11.exe:0xC0000005:执行位置0x89012914时发生访问冲突,在0x89012914。如果存在此异常的处理程序,则程序可以安全地继续运行。"

这是我目前掌握的代码,有什么明显的地方我忽略了吗?

int findKey(string& file);
int main()
{
    string inputFileName;

    cout << "Input file name: ";
    getline(cin, inputFileName);
    findKey(inputFileName);


}
int findKey(string& file)
{
    string reply;
    ifstream inFile;
    char character;
    int count[26] = { 0 };
    int nGreatest = 0;
    inFile.open(file.c_str());
    if (!inFile.is_open())
    {
        cout << "Unable to open input file." << endl;
        cout << "Press enter to continue...";
        getline(cin, reply);
        exit(1);
    }
    while (inFile.peek() != EOF)
    {
        inFile.get(character);
        cout << character;
        if (int(character) >= 65 || int(character) <= 90)
        {
            count[(int(character)) - 65]++;
        }
        else if (int(character) >= 97 || int(character) <= 122)
        {
            count[(int(character)) - 97]++;
        }
    }
    for (int i = 0; i < 26; i++)
    {
        if (count[i] > nGreatest)
            nGreatest = count[i];
    }
    cout << char(nGreatest) << endl;
    return 0;
}
if (int(character) >= 65 || int(character) <= 90)

由于换行符'n'是小于或等于90的ASCII 10,因此此if语句的求值结果为true,并且。。。

count[(int(character)) - 65]++;

尝试递增count[10-65]count[-55]。从这一点开始,事情几乎偏离了轨道(因为每个角色都至少是65,或者小于或等于90,所以这将始终计算为true)。

附言:我只用了几分钟的时间就找到了这个bug,使用调试器,一次一行地遍历代码(我自己无法立即看到它),并检查所有变量。您应该花一些时间学习如何使用调试器。这样就更容易找到自己的虫子,而不必向管道间的陌生人寻求帮助。