yes again, because I recently asked a very similar question (how to read a comma-separated list of integers), but this time I'm stuck on reading lines of strings that consists of comma-separated data. It sure must be trivial to convert my previous code that handled integers to instead handle strings of data chunks instead, right?
Ok, so I read data from a file or stdin that has many lines containing words that are separated by commas, for example:
hello,this,is,firstrow,sdf763
this,is,2nd,row
and,so,on314
So, my idea is simply to read lines of data from an istream using ranges::getlines (or ranges::istream_view), pipe each line to the split view adaptor splitting on commas in order to get the words (as a range of ranges, which I then join) and finally transform/decode each word that is then put into a vector. IMHO it should be super simple, just like:
std::string decode(const std::string& word);
int main()
{
using namespace ranges;
auto lines = getlines(std::cin); // ["hello,this,is,firstrow,sdf763" "this,is,2nd,row" "and,so,on314" ...]
auto words = lines | view::split(","); // [["hello" "this" "is" "firstrow" "sdf763"] ["this" "is" "2nd" "row"] [...]]
auto words_flattened = words | view::join; // ["hello" "this" "is" "firstrow" "sdf763" "this" "is" "2nd" "row" ...]
auto decoded_words = words_flattened | view::transform([](const auto& word){
return decode(word);
}) | to_vector;
for (auto word : decoded_words) {
std::cout << word << "\n";
}
std::cout << std::endl;
}
But no, this does not work and I cannot figure out why! The split view adaptor seem to not split the lines at all because the whole line is passed as an argument to transform - why is that?? I'm obviously still learning ranges and still miss some basic concepts it seems... I sure would appreciate if someone could explain what is going on, thanks in advance!
The link to my previous SO-question: Using range-v3 to read comma separated list of numbers