arrays - Parsing strings in C++ by multiple delimiters -
i have string object like:
string test = " [3, 4, 8, 10, 10]\n[12]\n[12, 10,\n 20] "
and trying parse 3 separate arrays equaling [3, 4, 8, 10, 10], [12], , [12,10, 20]. have parsed comma separated integers array before how go parsing one. unfortunately data have can have newlines mid array otherwise use "getline" function(when reading file string) , ignore brackets.
it seems need first each array own string delimited brackets, , parse each of comma delimination array of integers. work?
if so, how split string brackets unknown number of other strings?
you can use streams , std::getline()
std::getline()
takes delimiter parameter:
int main() { std::string test = "[3, 4, 8, 10, 10]\n[12]\n[12, 10,\n 20]"; // make data stream (could std::ifstream) std::istringstream iss(test); // working vars std::string skip, item; // between square braces // skip opening '[' getline item closing ']' while(std::getline(std::getline(iss, skip, '['), item, ']')) { // item = "3, 4, 8, 10, 10" // store numbers in vector (not array) std::vector<int> v; // convert item stream std::istringstream iss(item); // separated commas while(std::getline(iss, item, ',')) v.push_back(std::stoi(item)); // display results std::cout << "list:" << '\n'; for(auto i: v) std::cout << "\t" << << '\n'; } }
output:
list: 3 4 8 10 10 list: 12 list: 12 10 20
Comments
Post a Comment