錯誤提示:std::invalid_argument 於內存位置 0x0042ef1c,通常由 stoi() 或 atoi() 處理非數字字符串引起。
fun_substr 函數按空格分割,但未處理連續空格、行尾換行符,導致字段解析錯位。
// 危險代碼:vec[i+4] 可能非純數字
c1[j].oil = stoi(vec[i+4].c_str());
vec.resize(9) 可能截斷數據或填充空字符串,導致後續索引越界。
void fun_substr(fstream &file, const string& sep, vector& vec) {
string line;
while (getline(file, line)) {
if (line.empty()) continue;
size_t start = 0;
size_t end = line.find(sep);
while (end != string::npos) {
string token = line.substr(start, end - start);
if (!token.empty()) vec.push_back(token);
start = end + sep.length();
end = line.find(sep, start);
}
string last = line.substr(start);
if (!last.empty()) vec.push_back(last);
}
}
int safeStoi(const string& s, int defaultVal = 0) {
try {
size_t pos;
int val = stoi(s, &pos);
return (pos == s.length()) ? val : defaultVal;
} catch (...) {
return defaultVal;
}
}
// 使用示例
c1[j].oil = safeStoi(vec[i+4]);