I am having trouble with parsing chars into seperate tokens

I am having trouble with parsing chars into seperate tokens. My code can only execute some commands which doesn\'t have space. For example, ps, ls, or date can be executed. However, it cannot execute ps -ael. Because there is a space in between. Here is my code,

#include <iostream>
#include <string>
#include<sstream>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<sys/types.h>
#define MAX_LINE 80
using namespace std;

int main()
{
   int should_run = 1;
   string s,s1,a;
   string arg[10];
   char *arr[10];

   while (should_run)
   {
       cout<< (\"ubos>\") ;  
       cin>> s1;
      
       {  
       istringstream f(s1);
       while (getline(f,s, \' \'))
      
       for(int i=0; i<10; i++)
           {
          
           arg[i] = s;
arr[i] = (char*)arg[i].c_str(); //converting string to char          
           arr[1] = NULL;
                      
           }
          
   pid_t pid =fork();
   int i;

   if(pid<0)
   {
       cout<<\"fork\"<<endl;
   }
   else if (pid == 0 )
   {
      
       cout<<\"child: \" << pid << endl;
       for(int i=0; i<10; i++)
           {
               execvp(arr[i],arr);
           }
      
   }
   else if(pid > 0 )
   {
       wait(NULL);
       cout<<\"parent \" << pid<<endl;
   }
       }  
   }  
  
   return 0;
}

Solution

#include <iostream>
#include <string>
#include<sstream>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<sys/types.h>
#define MAX_LINE 80
using namespace std;

int main()
{
   int should_run = 1;
   string s,s1,a;
   string arg[10];
   char *arr[10];

   while (should_run)
   {
       cout<< (\"ubos>\") ;  
       cin>> s1;
      
       {  
       istringstream f(s1);
       while (getline(f,s, \' \'))
      
       for(int i=0; i<10; i++)
           {
          
           arg[i] = s;
arr[i] = (char*)arg[i].c_str(); //converting string to char          
           arr[1] = NULL;
                      
           }
          
   pid_t pid =fork();
   int i;

   if(pid<0)
   {
       cout<<\"fork\"<<endl;
   }
   else if (pid == 0 )
   {
      
       cout<<\"child: \" << pid << endl;
       for(int i=0; i<10; i++)
           {
               execvp(arr[i],arr);
           }
      
   }
   else if(pid > 0 )
   {
       wait(NULL);
       cout<<\"parent \" << pid<<endl;
   }
       }  
   }  
  
   return 0;
}

I am having trouble with parsing chars into seperate tokens. My code can only execute some commands which doesn\'t have space. For example, ps, ls, or date can
I am having trouble with parsing chars into seperate tokens. My code can only execute some commands which doesn\'t have space. For example, ps, ls, or date can
I am having trouble with parsing chars into seperate tokens. My code can only execute some commands which doesn\'t have space. For example, ps, ls, or date can

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site