I have an array 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
?
thx, JNK
I have an array 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
?
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).
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:
// 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);