Kagaratsch
Kagaratsch

Reputation: 1023

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++?

Upvotes: 1

Views: 395

Answers (2)

cigien
cigien

Reputation: 60412

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.

Upvotes: 1

qubix00n
qubix00n

Reputation: 157

Assuming that a std::vector can be used, you can try this:

std::vector<int> integers;
int currentNumber = 0;
for(char c = ' ', int i = 0; i < MAX_SIZE; i++) {
    c = buffer[i];
    if(c == ',') {
        integers.push_back(currentNumber);
        currentNumber = 0;
    } else {
        currentNumber *= 10;
        currentNumber += c - '0';
    }
}
integers.push_back(currentNumber);

Upvotes: 4

Related Questions