Search code examples
c++arrayscharint

C++ convert char array of digits and commas to list of integers?


I have a socket setup in C++ that receives a stream of chars in a buffer array

char buffer[MAXSIZE];

the characters in buffer can only be digits 0,1,...,9 or a comma ,. I would like to convert an example buffer content such as

buffer = {'1','2' , ',' , '3' , ',' , '5','6' , ...};

where the final char position is stored in a variable len, to a list of integers

integers = {12 , 3 , 56};

I can hack together a dumb way of doing this by iterating through the list of chars, taking each digit, multiplying it by 10 and adding the next digit, until I encounter a comma ,. But I guess this approach would be too slow for large data rate.

What is the proper way of doing this conversion in C++?


Solution

  • If you can use the range-v3 library, you could do this:

    namespace rs = ranges;
    namespace rv = ranges::views;
    
    auto integers = buffer 
                    | rv::split(',') 
                    | rv::transform([](auto&& r) { 
                          return std::stoi(r | rs::to<std::string>); 
                      }) 
                    | rs::to<std::vector<int>>;
    

    Here's a demo.