内存位置出现Microsoft C++异常:std::out_of_range

Microsoft C++ exception: std::out_of_range at memory location

本文关键字:std out of range 异常 位置 Microsoft C++ 内存      更新时间:2023-10-16

我试图使用find((和substr((输出文件中的特定行,只是想看看它是否有效。正如你所看到的,我是一个相当初学者,所以我会感谢任何对我的代码的评论或提示。

inFile.open("config.txt");
string content;
while (getline(inFile, content)){
if (content[0] && content[1] == '/') continue;
size_t found = content.find("citylocation.txt");
string city = content.substr(found);
cout << city << 'n';
}

以下摘录的几点注释:

content[0] && content[1] == '/'

当您编写content[0]content[1]时,假设位置0和1的字符存在,但事实并非如此。您应该将此代码包装在类似if (content.size() >= 2){ ... }的条件中,以保护自己不访问不存在的字符串内容。

其次,正如目前所写的,由于逻辑AND运算符&&的工作方式,此代码将把content[0]转换为bool。如果你想检查第一个和第二个字符都是'/',你应该写content[0] == '/' && content[1] == '/'

此外,在以下片段中:

size_t found = content.find("citylocation.txt");
string city = content.substr(found);

如果在字符串中找不到"citylocation.txt",该怎么办?CCD_ 10通过返回特殊值CCD_。您应该对此进行测试,以检查是否可以找到子字符串,再次防止自己读取无效的内存位置:

size_t found = content.find("citylocation.txt");
if (found != std::string::npos){
std::string city = content.substr(found);
// do work with 'city' ...
}