这是我的部分代码这个矢量分裂: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