lundi 2 octobre 2017

C++ Split a string by blank spaces unless it is enclosed in quotes

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 words within the quotes 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:

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 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);

Aucun commentaire:

Enregistrer un commentaire