-1

只要我添加以下代码,该程序就会结束显示此错误消息:

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;
  }



4

1 回答 1

2

length比字符串中的单词数少一,因为您只计算空格数。这意味着您的最终filesNameArr[number] = word会导致未定义的行为,并且可能会破坏堆栈。

string filesNameArr[length];使用一个无效的 C++ 可变长度数组。如果您使用 astd::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::stringstreams 内置的从字符串中读取单词的功能来简化此操作:

std::stringstream sinput(input);
std::vector<std::string> filesNameArr;
std::string word;
while (sinput >> word)
{
  filesNameArr.push_back(word);
}
于 2020-08-23T08:49:33.123 回答