将用户输入拆分为向量中的两个单词

Split user input into two words in a vector

本文关键字:单词 两个 输入 用户 拆分 向量      更新时间:2023-10-16

基本上,我希望程序允许用户输入两个单词,然后将其分割成一个向量。例如,如果用户输入:"Hello world",程序将获取单词"Hello"answers"world",并将它们存储在一个向量中。问题是,我对矢量不是很有经验,所以我不知道从哪里开始。下面是我到目前为止的代码:

#include <iostream>
#include <vector>
using namespace std;
void command_case();
string userIn;
int x = 0;
int main()
{
    while(userIn != "QUIT")
    {
        cout << "What shall I do?" << endl;
        cin >> userIn;
        cout << "Your raw command was: " << userIn << endl;
        command_case();
    }
}
void command_case()
{
    vector<char> Search;
    vector<string> command;
    char space = ' ';
    for(int i = 0; i < userIn.size(); ++i)
    {
        if(userIn[i] != space)
        {
            userIn[i] = toupper(userIn[i]);
        }
        if(userIn[i] == space)
        {
            Search.push_back(userIn[i]);
        }
    }
    command.push_back(userIn);
    cout << command[x] << endl;
}

如果我输入"Hello world",我得到这个:

What shall I do?
Hello world
Your raw command was: Hello
HELLO
What shall I do?
Your raw command was: world
WORLD

但我想找这个:

What shall I do?
Hello world
Your raw command was: Hello world
HELLO WORLD
谁能给我解释一下我做错了什么?

更改以下代码行

cin >> userIn;

getline(cin, userIn);