[英]convert chars form char array to integer in C
從像 {T,E,S,T,1,2,3,E,N,D} 這樣的字符數組中,我需要從某些位置獲取一個整數。 按照示例,我想從位置 4、5、6 中獲取一個整數。因此,myInt = 123。我嘗試了以下方法,但沒有得到所需的整數。
char receivedata[bytes];
concatVars = concatenate(atoi(receivedata[6] - '0', receivedata[7] - '0');
concatVars = concatenate(concatVars, receivedata[8] - '0');
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
這應該做你想做的:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int arrToInt(char* arr, int len) {
int toRet = 0;
for(int i = 0; i < len; i++) {
if (isdigit(arr[i])) {
toRet *= 10;
toRet += arr[i] - '0';
}
}
return toRet;
}
int main(int argc, char* argv[]) {
char test[] = {'T', 'E', 'S', 'T', '1', '2', '3', 'E', 'N', 'D'};
int asInt = arrToInt(test, 10);
printf("Got: %d\n", asInt);
}
輸出(使用 -std=c99 編譯以使int i = 0
內聯聲明工作):
得到:123
這樣做的一種方法是:
int myInt = (((int)myArray[4] - 48) * 100) + (((int)myArray[5] - 48) * 10) + (((int)myArray[6] - 48) * 1);
請注意,48 是數字 0 的 ASCII 位置,因此通過將字符轉換為 int,然后減去 48,您可以獲得數值。
標准庫的字符串到整數轉換函數(例如strtol
)一旦到達輸入字符序列中的非數字字符就會自動停止。 所以你所要做的就是告訴這樣的函數從哪里開始。 在您的情況下,這將執行轉換
const char *s = "TEST123END";
long myLong = strtol(s + 4, NULL, 10);
int myInt = myLong;
您只需要處理可能的錯誤。
這是一種方法:
int myInt = atoi(&myArray[4]);
添加到 ced-b 的響應中,我更喜歡這種語法:
myArray[5] - '0'
也就是說,明確表示您正在減去“0”。
注意:我在字符串中使用了特定的偏移量,因為 OP 要求:“我需要從某些位置獲取一個整數”,我將其解釋為字符串中的特定偏移量。 根據接受的答案,我似乎已經將其解釋為錯誤。
#include <stdio.h>
#include <string.h>
int main(){
char *str = "TEST123END";
char s4_6[4] = {0};
int n;
memcpy(s4_6, str+4, 3);
//if(1==sscanf(str, "%*[^0-9]%d", &n))
//if(1==sscanf(str+4, "%d", &n))
if(1==sscanf(s4_6, "%d", &n))
printf("%d\n", n);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.