簡體   English   中英

字符數組轉換為int

[英]Char-array to int

我有一個數組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

您可以結合使用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;
}

產出

Heading: 27
Pitch:   -112
Roll:    95

http://ideone.com/SUutl

據我了解,您知道第一個條目的寬度為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM