首页 > 解决方案 > Microsoft C++ 异常:内存位置的 std::out_of_range

问题描述

我试图使用 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';

}

标签: c++fstream

解决方案


关于以下摘录的几点说明:

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

当您编写content[0]andcontent[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"在字符串中找不到应该怎么办?std::string::find通过返回特殊值来处理这个问题std::string::npos。您应该对此进行测试以检查是否可以找到子字符串,以防止自己读取无效的内存位置:

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

推荐阅读