简体   繁体   中英

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

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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM