[英]Char-array to int
I have an array char input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};
我有一个数组
char input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};
How do I convert input[0,1,2] to int one = 27
, input[3,4,5,6] to int two = -112
and input[7,8,9,10] to int three = 95
? 如何将输入[0,1,2]转换为
int one = 27
,如何将输入[3,4,5,6]转换为int two = -112
和将输入[7,8,9,10]转换为int three = 95
?
thx, JNK thx,JNK
You can use a combination of strncpy()
to extract the character range and atoi()
to convert it to an integer (or read this question for more ways to convert a string to an int). 您可以结合使用
strncpy()
提取字符范围和atoi()
将其转换为整数(或阅读此问题以获取更多将字符串转换为int的方法)。
int extract(char *input, int from, int length) {
char temp[length+1] = { 0 };
strncpy(temp, input+from, length);
return atoi(temp);
}
int main() {
char input[11] = {'0','2','7','-','1','1','2','0','0','9','5'};
cout << "Heading: " << extract(input, 0, 3) << endl;
cout << "Pitch: " << extract(input, 3, 4) << endl;
cout << "Roll: " << extract(input, 7, 4) << endl;
}
Outputs 产出
Heading: 27
Pitch: -112
Roll: 95
As I understand your comment, you know that the first entry is 3 digits wide, the second and third are 4 digits wide: 据我了解,您知道第一个条目的宽度为3位,第二和第三位的宽度为4位:
// not beautiful but should work:
char buffer[5];
int one = 0;
int two = 0;
int three = 0;
// read ONE
memcpy(buffer, input, 3);
buffer[3] = '\0';
one = atoi(buffer);
// read TWO
input += 3;
memcpy(buffer, input, 4);
buffer[4] = '\0';
two = atoi(buffer);
// read THREE
input += 4;
memcpy(buffer, input, 4);
buffer[4] = '\0';
three = atoi(buffer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.