0

So I have a semiworking program where I read in user input using

getline(std::cin, userinput, '\n')

I then send the input to a std::vector<std::string> subStrs to break up the input from the user so each command element is seperate

and then push them all to a std::vector<char*> params so I can pass it to execvp(..)

This seems very inefficient to me but is there a better way of getting the user input into the std::vector<char*> without all of the intermediate steps?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
user3577756
  • 643
  • 1
  • 9
  • 13
  • You program should be simple and readable first of all, then only if you have issue with performance you should optimize it – Slava Feb 17 '16 at 21:13
  • Unless you're processing the data, you might just pipe the output from your one process directly into the other. Reading lines is really only relevant if you have to do some alteration, otherwise it's just buffered data. – tadman Feb 17 '16 at 21:19
  • I have to allow for the user to type in ls -l > txt.txt for example and pass ls -l to execvp(..) while opening txt.txt for output of ls -l – user3577756 Feb 17 '16 at 21:25
  • Unless `execvp` operates differently under `c++` than `c`, what it needs is a `NULL` terminated `char **args` [or `char *argl[...]`]. I'm not sure that `vector` can provide that directly [if so, all to the good]. So, if you're trying to skip [multiple] conversion steps, you may want to use some lower level functions. See my recent answer here: http://stackoverflow.com/questions/35422929/proper-memory-allocation-for-strings/35424246#35424246 as the function is quite similar to what you need [using `stdin` instead of a file stream and removing the outer loop]. – Craig Estey Feb 17 '16 at 23:38

1 Answers1

0

This solution seems to work for what I was wanting. Not sure how great of a solution it is though.

std::vector<std::string> processString(std::string userInput)
{
   int j = 0;
   std::vector<std::string> subStrs;
   for (int i = 0; i < userInput.size(); i++)
   {
      bool sameSeq = false;
      if (isalnum(userInput[i]) || ispunct(userInput[i]))
      {
         subStrs.resize(subStrs.size() + 1);
         while (isalnum(userInput[i]) || ispunct(userInput[i]))
         {
            subStrs[j].push_back(userInput[i]);
            sameSeq = true; 
            i++;
         }
         if (sameSeq)
         {
            subStrs[j].push_back('\0');
            j++;   
         }
      }

   }
   return subStrs;
}
user3577756
  • 643
  • 1
  • 9
  • 13