我有一个问题。
以前在我的问题之一。
位掩码编码为:
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));
}
我通过这种方法使用:
vector<string> x = split(receiveClient, '#');
但是,当我意识到分隔符固定为 # 时,在某个时间点,我需要使用“:”或其他分隔符来分割字符串,所以我的问题是,如何更改函数以便它可以接受我通过的分隔符在。
如
vector<string> x = split(receiveClient, ':');
我面临的一些问题是“分段核心转储错误”
不工作的版本
if(action=="auth")
{
myfile.open("account.txt");
while(!myfile.eof())
{
getline(myfile,sline);
vector<string> check = split(sline, ':');
logincheck = check[0] + ":" + check[3];
cout << logincheck << endl;
if (logincheck==actionvalue)
{
sendClient = "login done#Successfully Login.";
break;
}
else
{
sendClient = "fail login#Invalid username/password.";
}
}
myfile.close();
}
运行上面的代码让我出错 - Segmentation Core Dump
这是我的 account.txt 文件
admin:PeterSmite:hr:password
cktang:TangCK:normal:password
但是,如果我将代码更改为不使用矢量拆分的旧版本,则代码可以顺利运行。没有分段核心转储。不同的是上面使用向量将字符串 sline 拆分为向量,然后使用它分配给字符串 logincheck
工作版(无矢量分割)
if(action=="auth")
{
myfile.open("account.txt");
while(!myfile.eof())
{
getline(myfile,sline);
//action value is in form of like demo:pass (user input)
if (sline==actionvalue)
{
sendClient = "login done#Successfully Login.";
break;
}
else
{
sendClient = "fail login#Invalid username/password.";
}
}
myfile.close();
}
我的问题是,我如何在没有分割核心转储的情况下分割它,以便使用向量分割的代码
vector<string> check = split(sline, ':');
logincheck = check[0] + ":" + check[3];
cout << logincheck << endl;