【发布时间】: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