内存位置出现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){ ... }
的条件中,以保护自己不访问不存在的字符串内容。
其次,正如目前所写的,由于逻辑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' ...
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- swig perl typemap(out) std::vector<std::string> 在 perl 中不返回所需的输出
- "friend std::ostream& operator<<(std::ostream& out, LinkedList& list)"是什么意思?
- 尝试同时写入 std:out 和文件
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- c ++如何使我.get() std::future out of a vector.
- 如何在 Linux 中将孩子的进程 std (out / err) 设置为父级
- fstream::open() Unicode 或非 ASCII 字符在 Windows 上不起作用(使用 std::ios::out)
- C++同时写入 std::out 和 std:clog
- Printing out std::map
- 将Std::vector通过ref / out从c#传递到c++
- QTextStream and std out
- 聚合'std::stringstream out'具有不完整的类型,无法定义 [C++]
- 以std:: Fstream::in | std:: Fstream::out | std:: Fstream::app