[英]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我在 C++ 中有一个套接字设置,它接收缓冲区数组中的字符 stream
char buffer[MAXSIZE];
the characters in buffer
can only be digits 0
, 1
,..., 9
or a comma ,
. buffer
中的字符只能是数字0
, 1
,..., 9
或逗号,
. 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其中最终字符 position 存储在变量
len
中,到整数列表
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 ,
.我可以通过遍历字符列表,获取每个数字,将其乘以 10 并添加下一个数字,直到遇到逗号
,
来组合一种愚蠢的方式来做到这一点。 But I guess this approach would be too slow for large data rate.但我想这种方法对于大数据速率来说太慢了。
What is the proper way of doing this conversion in C++?在 C++ 中进行此转换的正确方法是什么?
Assuming that a std::vector
can be used, you can try this:假设可以使用
std::vector
,你可以试试这个:
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:如果你可以使用 range-v3 库,你可以这样做:
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>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.