Hey guys. This is my first time doing anything like this so please don't be too harsh on me. So, I am trying to write a shell. The first step is to take the users input command and split it up into arguments.
So this is what I've got:
[tag]
[/tag]Code:void parse(string something)
{
int cnt = 0;
char *argv[11];
string val, part;
stringstream unit(something);
while(getline(unit, val, ' ') && cnt < 10)
{
part = val;
argv[cnt] = (char*)part.c_str();
cnt++;
}
argv[cnt] = NULL;
}
So, I want the method to take the string and split it into parts. The delimiter is an empty space between words. Then, I want it to take each part and throw it into the *argv[]. After its got all the parts the very last part put into the array should be followed by a NULL. Seems alright logically to me.
But, if I were to put in a for loop to read through the array the result I get is not at all what I want.
For example if I put in "This is my world" and appended this for loop to the end of that method:
[tag]
[/tag]Code:for(int i = 0; argv[i] != NULL; i++)
cout << argv[i] << endl;
OR
for(int i = 0; i < cnt; i++)
cout << argv[i] << endl;
I should get this as an output:
This
is
my
world
But, in most cases I might get the last 3 lines but the first one will be empty. In others the words will get mixed up or there will be doubles even though i did not put a particular word in my input multiple times. I don't understand why this happens. Any help would be appreciated.