字符数组为int [英] Char-array to int

查看:126
本文介绍了字符数组为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组炭输入[11] = {'0','2','7',' - ','1','1','2',' 0','0','9','5'};

我如何将输入[0,1,2]到 INT 1 = 27 ,输入[3,4,5,6]到诠释2 = -112 输入[7,8,9,10]到 INT 3 = 95

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

推荐答案

您可以使用函数strncpy的组合()来提取字符范围和与atoi()将其转换为整数(或读的这个问题更多的方式将一个字符串到int转换)。

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

输出

Heading: 27
Pitch:   -112
Roll:    95

http://ideone.com/SUutl

这篇关于字符数组为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆