這是我的部分代碼這個矢量分裂:C++中什麼是錯在While循環
if(action=="auth")
{
myfile.open("account.txt");
while(!myfile.eof())
{
getline(myfile,sline);
vector<string> y = split(sline, ':');
logincheck = "";
logincheck = y[0] + ":" + y[3];
if (sline==actionvalue)
{
sendClient = "login done#Successfully Login.";
break;
}
else
{
sendClient = "fail login#Invalid username/password.";
}
y.clear();
}
myfile.close();
}
如果我沒有這個
logincheck = y[0] + ":" + y[3];
的代碼將不會有任何的分割核心轉儲錯誤,但是當我添加該行時,它將完全錯誤。
我account.txt是如下:
admin:PeterSmite:hr:password
cktang:TangCK:normal:password
分割功能:
std::vector<std::string> split(std::string const& str, std::string const& delimiters = "#") {
std::vector<std::string> tokens;
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
std::vector<std::string> split(std::string const& str, char const delimiter) {
return split(str,std::string(1,delimiter));
}
您是否在調試器中檢查了分離器是否正常工作? – Dani 2012-08-12 14:04:21
在碰撞時y是什麼?我的猜測是你的文件在最後有一個空行,所以你的split函數不會返回那行的4個元素。如果發生這種情況,那麼您正在訪問不存在的矢量元素。 – cbranch 2012-08-12 14:07:03