提问者:小点点

C++拆分字符串函数给出意外输出


std::vector<char*> Split(std::string input) {
  std::vector<char*> ret;
  std::istringstream f(input);
  std::string s;
  while (getline(f, s, ' ')) {
    ret.push_back((char*)s.c_str());
  }
  return ret;
}

这个函数的意思是取一个字符串并把每个单词放到一个向量中。 但是假设我将ls-l作为字符串。 它应该返回一个包含两个元素ls-l的向量。 相反,它返回一个包含两个元素-LL的向量。 谁能帮我拿一下这个吗?


共3个答案

匿名用户

复制指针并不意味着复制被指向的东西。

看来你得抄袭这些字符串。

#include <cstring> // for strlen() and strcpy()

std::vector<char*> Split(std::string input) {
  std::vector<char*> ret;
  std::istringstream f(input);
  std::string s;
  while (getline(f, s, ' ')) {
    char* buf = new char[strlen(s.c_str()) + 1]; // +1 for terminating null-character
    strcpy(buf, s.c_str());
    ret.push_back(buf);
  }
  return ret;
}

匿名用户

您正在向量中存储指向字符串的指针,但字符串s在函数退出时被破坏。 因此您正在存储指向已删除对象的指针。

使用字符串而不是指针。 字符串很容易正确复制,不像指针。 试试这个

std::vector<std::string> Split(std::string input) {
  std::vector<std::string> ret;
  std::istringstream f(input);
  std::string s;
  while (getline(f, s, ' ')) {
    ret.push_back(s);
  }
  return ret;
}

匿名用户

您从另外两个答案中得到了您的答案,但我有另一种方法可以拆分字符串(称为字符串标记化):

std::vector<std::string> split(std::string text) {
    std::vector<std::string> words;

    std::string temp{};
    for (int i=0; i < text.size(); ++i) {
        if (text[i] != ' ') {
            temp.push_back(text[i]);
            if (i ==  text.size()-1) {
                words.push_back(temp);
            }
        }
        else if (temp.size() != 0) {
            words.push_back(temp);
            temp.clear();
        }
    }

    return words;
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|拆分|字符串|函数|给出|意外|输出)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?