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

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

我试图使用 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){ ... } 之类的条件中,以防止您访问不存在的字符串内容。

其次,正如目前所写的那样,由于逻辑与运算符 && 的工作方式,此代码会将 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' ...
}