Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Parsing number from std::string [duplicate]

Tags:

c++

I need to iterate through a shopping list which I have put into a vector and further separate each line by the quantity and item name. How can I get a pair with the number as the first item and the item name as the second?

Example:

vector<string> shopping_list = {"3 Apples", "5 Mandarin Oranges", "24 Eggs", "152 Chickens"}

I'm not sure how big the number will be so I can't use a constant index.

Ideally I would like a vector of pairs.


1 Answers

You can write a function to split quantity and item like following:

#include <sstream>

auto split( const std::string &p ) {
    int num;
    std::string item;

    std::istringstream  ss ( p);
    ss >>num ; // assuming format is integer followed by space then item
    getline(ss, item); // remaining string
    return make_pair(num,item) ;
}

Then use std::transform to get vector of pairs :

std::transform( shopping_list.cbegin(),
                   shopping_list.cend(),
                   std::back_inserter(items), 
                   split );

See Here

like image 100
P0W Avatar answered Oct 21 '25 03:10

P0W