C++ 用空格分割一个字符串,除非它用引号括起来并存储在一个向量中

Mas*_*stR 2 c++ string split vector c++11

我有一个需要用户输入的提示。我想接受这个用户输入并将每个单词存储在一个向量中,用空格分割,除非引号之间包含一组单词,在这种情况下,我希望引号内的所有单词都计为 1。

例如,如果用户输入以下内容:

12345 Hello World "This is a group"
Run Code Online (Sandbox Code Playgroud)

然后我希望向量存储:

vector[0] = 12345
vector[1] = Hello
vector[3] = World
vector[4] = "This is a group"
Run Code Online (Sandbox Code Playgroud)

我有以下代码,它按空格拆分用户输入并将其存储在向量中,但我无法弄清楚如何将引号内的所有文本都算作一个。

 string userInput

 cout << "Enter a string: ";
 getline(cin, userInput);

string buf; 
stringstream ss(userInput); 

vector<string> input;

while (ss >> buf){
    input.push_back(buf);
Run Code Online (Sandbox Code Playgroud)

我想在用户输入引号的单词周围保留引号。我还想将结果保存到向量中,而不仅仅是将字符输出到屏幕

seh*_*ehe 5

C++14 内置了它:http : //en.cppreference.com/w/cpp/io/manip/quoted

Live On Coliru

#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>

int main(void) {
    std::istringstream iss("12345 Hello World \"This is a group\"");
    std::vector<std::string> v;
    std::string s;

    while (iss >> std::quoted(s)) {
        v.push_back(s);
    }

    for(auto& str: v)
        std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

印刷

12345
Hello
World
This is a group
Run Code Online (Sandbox Code Playgroud)