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

is there a way i can fix this?

void input::read_line()
{
  string command;
  while(command != "exit")
    {
      cout <<"Enter a command" << endl;
      cin >> command;
      string buf;
      stringstream ss(command);

      vector<string> tokens;
      while(ss >> buf)
        tokens.push_back(buf);

      cout << tokens[0] << endl;
      cout << tokens[1] << endl;
    }

Recommended Answers

All 6 Replies

You can't use cin >> for strings that may contain spaces because cin will stop at the first white space (spaces and tabs) character. If you want white space in the string then use getline()

You can't use cin >> for strings that may contain spaces because cin will stop at the first white space (spaces and tabs) character. If you want white space in the string then use getline()

thanks, how would i do for a fixed number of tokens, lets say like 10

just use getline() instead of cin >>. The rest should work as it is, except at the end when you want to display all of the tokens

for(int i = 0; i < tokens.size(); i++)
   cout << tokens[i] << '\n';

or if you want to use an iterator

vector<string>::iterator it;
for( it = tokens.begin(); it != tokens.end(); it++)
   cout << *it << '\n';

i mistakenly repeated my reply check post below

thanks i actually dont need to print it, it was just to test it,
my code will work if there is more than 1 word input for example cd hello
but how would i handle it its only 1 word like cd

string command;
  while(command != "exit")
    {
      cout <<"Enter a command" << endl;
      getline(cin, command);
      string buf;
      stringstream ss(command);
      vector<string> tokens;

      while(ss >> buf)
        tokens.push_back(buf);

      if(tokens[0] == "cd")
        {
// do something
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.