【问题标题】:After compiling the code it crashes (couldn't get why)编译代码后它崩溃(不明白为什么)
【发布时间】:2015-05-06 10:55:27
【问题描述】:

当我使用带有常量字符串的 StrSplit 函数时,它工作得很好。但是当我从文件中读取该行然后将其用作 StrSplit 函数的字符串时,我的程序崩溃了。以下是代码和错误截图。

string Read_from_file(){

//load the text file and put it into a single string:
std::ifstream in("test.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string test = buffer.str();
std::cout << test << std::endl << std::endl;
return test;
}
// split the given string according to give delimeters
vector<string> &StrSplit( string inStr, string sepStr, vector<string>       &outStrVec) {
char * comp;
char * buffer = new char[ strlen( inStr.c_str() ) ];
strcpy( buffer, inStr.c_str() );
comp = strtok ( buffer, sepStr.c_str() );
while ( comp != NULL ) {
    outStrVec.push_back(comp);
    comp = strtok ( NULL, sepStr.c_str() );
}
delete[]  comp;
delete[]  buffer;
return outStrVec;
}

vector<string> StrSplit( string inStr, string sepStr ) {
vector<string> outStrVec;
return StrSplit( inStr, sepStr, outStrVec );
![enter image description here][2]}

int main( ) {
Read_from_file();
string fileinput = Read_from_file();
vector<string> v;
string inStr = fileinput;
v = StrSplit( inStr, "|#$ *@.&\"!^01" );
for (unsigned int i = 0; i < v.size(); ++i) {
    cout << v[i] << '\n';
}

}

【问题讨论】:

  • 例如,如果我使用 inStr="bob010101*******was*....there"; v = StrSplit( inStr, "|#$ *@.&\"!^01" ); 在输出上我会得到(Bob 在那里)但是当我使用从文件中解析的字符串时,我得到了显示的错误图片。
  • 我不愿意开始指出问题,因为你需要去pick up a good book。但是当你从inStr 创建buffer 时,你不会在最后为NUL 留出空间。
  • @BoBTFish 无法理解您的意思,请您再解释一下,或者如果您在代码中显示它会很棒。提前致谢
  • 请正确格式化您的代码sn-p。
  • @Barryj 和 Henrik 的回答一样。

标签: c++ string string-split


【解决方案1】:

缓冲区太小,无法包含包含终止 0 字符的字符串。

改变

char * buffer = new char[ strlen( inStr.c_str() ) ];

到

char * buffer = new char[ strlen( inStr.c_str() ) + 1];

并且不要在没有new 的指针上调用delete(删除delete[] comp)。

实际上,我永远不会在 C++ 中使用strtok。

【讨论】:

  • 感谢它正在工作。同时感谢 Bob 以及您的时间。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 2014-08-12
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多