Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Split a string by blank spaces unless it is enclosed in quotes and store in a vector [duplicate]

I have a prompt that takes user input. I want to take this user input and store each word in a vector, splitting by a blank space, unless a group of words is contained between quotes, in which case I want all of the terms within the sections to count as 1.

For example, if the user enters the following:

12345 Hello World "This is a group"

Then I want the vector to store the following:

vector[0] = 12345
vector[1] = Hello
vector[3] = World
vector[4] = "This is a group"

I have the following code, which splits the user input by blank space and stores it in a vector, but I am having trouble figuring out how to make all text within quotes count as one.

 string userInput

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

string buf; 
stringstream ss(userInput); 

vector<string> input;

while (ss >> buf){
    input.push_back(buf);

I want to keep the quotes around the words where the user enters the passages. I also want to save the results to a vector rather than output the characters to the screen.

like image 841
MastRofDsastR Avatar asked Sep 14 '25 10:09

MastRofDsastR


1 Answers

C++14 has it built in: 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;
}

Prints

12345
Hello
World
This is a group
like image 150
sehe Avatar answered Sep 17 '25 00:09

sehe