问题描述
Process returned -1073741819 (0xC0000005)
如果我分别运行这些代码,那么它们都可以工作。
我也使用了sstream
和数组,但是结合起来它们不能正常工作。
#include <sstream>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string input = "touch world.txt this.txt is.txt sentence.txt";
string word;
int length = 0;
for(int a = 0;a<input.length();a++){
if(input[a] == ' '){
length++;
}
}
string filesNameArr[length];
int number = 0;
// hello world this is sentence
for(auto x:input)
{
if(x==' ')
{
filesNameArr[number] = word;
word.erase();
number++;
}
else
word=word+x;
}
filesNameArr[number] = word;
number = 0;
//when i add the below code it generates error and stops
ofstream outFile[41];
stringstream sstm;
for (int i=0;i<41 ;i++)
{
sstm.str("");
sstm << "subnode" << i;
outFile[i].open(sstm.str().c_str());
}
return 0;
}
解决方法
length
比字符串中的单词数少一个,因为您只计算空格数。这意味着您最终的filesNameArr[number] = word
会导致未定义的行为,并且可能会破坏堆栈。
string filesNameArr[length];
使用的可变长度数组不是有效的c ++。如果您使用std::vector
,则可以完全跳过单词的初始计数:
std::vector<std::string> filesNameArr;
for(auto x:input)
{
if(x==' ')
{
filesNameArr.push_back(word);
word.erase();
}
else
{
word+=x;
}
}
filesNameArr.push_back(word);
您可以使用内置的std::stringstream
来读取字符串中的单词,以使其变得更加简单:
std::stringstream sinput(input);
std::vector<std::string> filesNameArr;
std::string word;
while (sinput >> word)
{
filesNameArr.push_back(word);
}