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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With