![](/img/trans.png)
[英]C++: Unhandled exception: std::out_of_range at memory location
[英]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"
,該怎么辦? std::string::find
通過返回特殊值std::string::npos
處理此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' ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.