-4
我有一個問題。C++如何使這個向量函數接受任何分隔符
以前對我的問題之一。
位掩碼編碼這樣的:
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();
}
運行上面的代碼版本讓我錯誤 - 分割核心轉儲
這是我的account.txt文件
admin:PeterSmite:hr:password
cktang:TangCK:normal:password
Howe如果我將代碼更改爲不使用向量拆分的舊版本,代碼可以順利運行。沒有分段核心轉儲。所不同的是上面使用矢量串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;
沒有什麼固定的分隔符。請嘗試一下。 – Mat 2012-08-12 13:22:37
我試過了,但我得到了分割錯誤。 – user1587149 2012-08-12 13:23:07
在你的代碼中,你正在調用一個不在這裏顯示的函數'splitz'。使用調試器查明段錯誤,並在你的問題中描述你的錯誤 - Stack Overflow不會爲你編寫所有的代碼,特別是當它已經存在時。 – Mat 2012-08-12 13:25:19