c++ - 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';
}
解决方案
关于以下摘录的几点说明:
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' ...
}
推荐阅读
- android - 应用程序未在后台运行时未收到推送通知
- angular - 如何使用 Angular Universal ssr 添加谷歌分析跟踪
- regex - 使用自定义函数查找列中的所有单词
- kademi - 如何将产品数据公开到 SPCRM 上的策略列表
- javascript - 无法从 Google App Engine 内部构建 React 应用程序
- react-native - 如何在具有其他属性 React-native 的 fetch 正文中将文件(docx,pdf)发送到服务器?
- python - selenium.common.exceptions.WebDriverException:消息:断开连接:通过 Python 收到带有 ChromeDriver 和 Selenium 的 Inspector.detached 事件
- z3 - z3 序列问题的策略
- c# - Entity Framework Core 中的循环引用。循环引用是好是坏?
- javascript - 为什么与一些较小尺寸的设备相比,较大尺寸的设备屏幕宽度更小?