我有一个数组char input[11] = {'0','2','7', '-','1','1','2', ,'0','0','9','5'};
如何将输入[0,1,2]转换为int one = 27
,输入[3,4,5,6]至int two = -112
并输入[7,8,9,10]至int three = 95
?
thx,JNK
答案 0 :(得分:5)
您可以使用strncpy()
的组合来提取字符范围,并使用atoi()
将其转换为整数(或读取this question以获取将字符串转换为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;
}
输出
Heading: 27
Pitch: -112
Roll: 95
答案 1 :(得分:0)
据我了解你的评论,你知道第一个条目宽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);