C++ 编译代码后会崩溃(不知道原因)
当我使用带常量字符串的StrSplit函数时,效果非常好。但当我从文件中读取该行,然后将其用作StrSplit函数的字符串时,我的程序崩溃了。以下是代码和错误屏幕截图C++ 编译代码后会崩溃(不知道原因),c++,string,string-split,C++,String,String Split,当我使用带常量字符串的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(); st
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';
}
从文件()读取字符串{
//加载文本文件并将其放入单个字符串中:
std::ifstream-in(“test.txt”);
std::stringstream缓冲区;
缓冲区缓冲区太小,无法包含包含终止0字符的字符串
改变
char * buffer = new char[ strlen( inStr.c_str() ) ];
到
并且不要对未添加的指针调用delete
(删除delete[]comp
)
实际上,我在C++中绝不会使用<代码> Strutok/代码>。例如,如果我使用的是“BiB010101 *** **……”;V= StruScript(ISTR),“$*$*@,&“^ ^ 01”);在Outputt上,我将得到(鲍伯在那里)但是当我使用我从文件中解析的字符串时,我得到了图像上显示的错误。我不愿意开始指出问题,因为你需要去。但是当你从
inStr
创建缓冲区时,你没有在最后为NUL
留下空间。@BoBTFish不明白你的意思,请解释一下再多一点,或者如果你在代码中显示它,那就太棒了。谢谢你,请正确格式化你的代码片段。@Barryj这和Henrik的答案一样。谢谢它起作用。同时感谢Bob,谢谢你的时间。感谢你的帮助
char * buffer = new char[ strlen( inStr.c_str() ) + 1];