i have a problem with my following code, note: this is just part of my code
when i run it, lets say i enter hello world
it will output:
hello
segmentation fault
You are assuming there will be at least two tokens in the 'tokens' vector. You must never make such assumptions, especially when coming from user input!
You're getting the segmentation fault because tokens[1] doesn't exist. The array is only 1 element big because you only put "hello" in it.
Remember the >> operator stops at whitespace, so when you say cin >> command you are only taking up to the first space... which is why you only get "hello". If you want to get the entire line, use getline:
getline( cin, command );
Also, you should never even allow the possibility of accessing outside of array bounds. If the user inputs fewer than 2 tokens, your program will fail. Check the size of tokens before you print, and make sure you never print past the end of the vector.
ok so i changed it but im still getting a segmentation fault
i did the following input:
hello all of you
and i get the following output
hello
all
of
you
segmentation fault
if(tokens[0] == "cd")
{
// i call a function here
}
so when the input is just one token "cd" it returns the home directory.
but if it has 2 inputs like cd hello it will go to that directory.
so the problem is that when i only input one token it gives me a segmentation fault
so basically what im trying to do is parse a command line and its arguments from user input