简体   繁体   中英

C++ Loading user input into vector

I am trying to create a command line app, where the user can type in commands and data, but I don't really get how istream_iterator is working, how can I get a whole input (until enter) into a vector? Right now it creates a new while loop on every word, that is not what is want.

int main(int argc, char* argv[])
{
    string buffer;      
    //vector<string> vbuff;
    CliHandler clihandler(argc, argv);
    int state = clihandler.State();
    while (state != CliHandler::STATE_EXIT) {

        cout << ">>";
            //Beolvasás
            cin >> buffer;
            stringstream sstream(buffer);
            istream_iterator<string> begin(sstream);
            istream_iterator<string> end;
            vector<string> vbuff(begin,end);

            copy(vbuff.begin(), vbuff.end(), std::ostream_iterator<string>(std::cout, "\n"));//test

            //vbuff = vector<string>((istream_iterator<string>(cin)), istream_iterator<string>());
            //copy(vbuff.begin(), vbuff.end(), std::ostream_iterator<string>(std::cout, "\n"));

            switch(clihandler.State(vbuff[0])) {
                          // [command] [data1] [data2] ...
            }
    }

    return 0;
}

Why don't you just use the argc and argv parameters? Something like this..(haven't tested)

int main(int argc, char* argv[])
{
    vector<string> vbuff(argc);
    for (int i = 0; i < argc; ++i)
    {
        vbuff[i] = argv[i];
    }

    // From here, you can use vbuff for your own purposes.
}

I m not very sure what u want(my poor english..), maybe you want to get input of the whole line until enter I think you can use cin.getline

    char mbuf[1024];
    cin.getline(buffer,1024);

Based on your comment: "I am reading input interactively. exit command would leave the while loop and end the program"

You'd be better off getting that simple loop to work first, before trying to process the input string.

std::string inputCommand;
while(inputCommand != "Exit")
{
    cin >> inputCommand;
    //do stuff with it
}

Then you could consider splitting and handling the string

bool shouldExit(false);
std::vector<std::string> inputsReceived;
while(!shouldExit)
{
    char delim ('#'); //here put whatever character your inputs are separated by
    std::string buffer;
    cin >> buffer;
    std::stringstream ss;
    ss << buffer;
    std::string item;
    while (std::getline(ss, item, delim))
    {
        if (item == "Exit") //case sensitive
        {
            shouldExit = true;
            break;
        }
        else
        {
            //do whatever with input
        }

        //if you want to keep a record of the inputs in a vector
        inputsReceived.push_back(item);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM