编译代码后它崩溃了(不明白为什么)
After compiling the code it crashes (couldn't get why)
当我将 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';
}
}
缓冲区太小,无法容纳包含终止字符 0 的字符串。
改变
char * buffer = new char[ strlen( inStr.c_str() ) ];
到
char * buffer = new char[ strlen( inStr.c_str() ) + 1];
并且不要在您没有 new
的指针上调用 delete
(删除 delete[] comp
)。
实际上,我永远不会在 C++ 中使用 strtok
。
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';
}
}
缓冲区太小,无法容纳包含终止字符 0 的字符串。
改变
char * buffer = new char[ strlen( inStr.c_str() ) ];
到
char * buffer = new char[ strlen( inStr.c_str() ) + 1];
并且不要在您没有 new
的指针上调用 delete
(删除 delete[] comp
)。
实际上,我永远不会在 C++ 中使用 strtok
。