通过函数读取文件时出现问题
Issue While Reading Files Through Function
我正试图为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,使用调试器,一次一行地遍历代码(我自己无法立即看到它),并检查所有变量。您应该花一些时间学习如何使用调试器。这样就更容易找到自己的虫子,而不必向管道间的陌生人寻求帮助。
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 编译要在英特尔Hyperscan中使用的.cc文件时出现问题
- 使用 seekg() 读取C++中的文件时出现问题
- sqlite3 和生成文件中的链接出现问题
- C++头文件和类实现出现问题
- 用户输入字符串的文件附加问题..C++
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 读取文件并将其存储在unordered_map中时出现问题
- 编译 llvm 插件时出现问题:llvm/Config/llvm-config.h:没有这样的文件或目录
- 我在使用C++文件时遇到了一些问题
- 在Linux上使用Clang / OLLVM交叉编译helloworld Windows可执行文件时的问题
- 将文件复制到自定义位置,存在字符串转换问题
- DirectX12 的问题:"d3dApp.h":没有这样的文件或目录
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 读取制表符分隔的文件时出现问题 C++
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 使用 RapidXML 解析大型 XML(大小大于 65 KB)文件时出现问题
- C++:读取.BMP文件时出现问题;文件结束时间早于预期