-4

我有一个问题。

以前在我的问题之一。

位掩码编码为:

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;
4

1 回答 1

0

我只是说,你读错了文件。eof()仅在读取文件末尾后返回 true。您正在阅读的最后一行是空的(如果您记得在最后一个数据之后添加换行符,就像您应该的那样)。

并且您应该检查空字符串,这在 90% 中是写得不好的代码段错误的原因(在处理字符串时)。你应该开始使用调试器,比如 gdb 来找出问题所在,而不是仅仅发布整个代码。

于 2012-08-13T00:16:39.747 回答