how to make our own function like touch in c++

-1

As soon as I add the below code this programs ends showing this error message:

Process returned -1073741819 (0xC0000005)

If I run those code separately then both of them work.

I used sstream and array too but combined they do not work properly.

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



c++
file
ofstream
sstream
asked on Stack Overflow Aug 23, 2020 by Phantasm • edited Aug 23, 2020 by Phantasm

1 Answer

2

length is one less than the number of words in your string as you are only counting the number of spaces. This means your final filesNameArr[number] = word causes undefined behaviour and will probably corrupt the stack.

string filesNameArr[length]; uses a variable length array which is not valid c++. If you use a std::vector instead you can skip the initial counting of the words completely:

std::vector<std::string> filesNameArr;
for(auto x:input)
{
    if(x==' ')
    {
      filesNameArr.push_back(word);
      word.erase();
    }
    else
    {                  
      word+=x;
    }
}
filesNameArr.push_back(word);

You can use std::stringstreams built in ability to read words from strings to make this even simpler:

std::stringstream sinput(input);
std::vector<std::string> filesNameArr;
std::string word;
while (sinput >> word)
{
  filesNameArr.push_back(word);
}
answered on Stack Overflow Aug 23, 2020 by Alan Birtles • edited Aug 23, 2020 by Alan Birtles

User contributions licensed under CC BY-SA 3.0