-2

I'm trying to implement a basic terminal (like bash), and I'm currently trying to take in user input (as if they were entering commands in bash) and split up each by spaces and put it in a vector so I can read from the vector and attend to each command one by one. I can't seem to get my code to compile, what am I doing wrong? (here's what I have so far):

#include <iostream>
#include <cstring>
#include <vector>
#include <string>
using namespace std;

int main(){
    vector<string> cmdline;
    string command = "";
    cout << '$';
    getline(cin, command);

    command.c_str();
    char* tokchar;
    tokchar = strtok(command, " ");


    while(tokchar){
        cmdline.push_back(tokchar);
        tokchar = strtok(NULL, " ");
    }
 return 0;
 }

Specifically, the compiler error is: cannot convert 'std::string' to 'char*'for argument 1 to 'char* strtok(char*, const char*)' It says the error is on the line where I set tokchar =...;

I'm not sure if this code will do what I'm hoping. How would I fix it and make it put all of the command line arguments into a vector separated by " "?

Happy Hippo
  • 102
  • 9

1 Answers1

1

You are using C++ types with a function that's more idiomatic to C. Consider boost::split for C++.

All of:

char* tokchar;
tokchar = strtok(command, " ");


while(tokchar){
    cmdline.push_back(tokchar);
    tokchar = strtok(NULL, " ");
}

could be replaced (without errors) by:

boost::split( cmdline, command, boost::is_any_of(" ") );
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180