![](/img/trans.png)
[英]Convert int to string, then fill the array with the converted elements
[英]convert string elements to an int array elements in c
我需要在項目中將char格式的字符串元素轉換為int格式的數組。 我使用以下函數,但是編譯后出現錯誤:
a[k] = atoi (str1[k]);
a[k] = strtol(str1[k],NULL,16);
K作為計數器。
error: #167: argument of type "char" is incompatible with parameter of type "const char *restrict"
這些函數采用字符串參數,而不是單個字符。
如果需要單個字符的值,則非常簡單:
a[k] = str1[k] - '0';
如果str[k]
是數字'7',則a[k]
的整數值為7。
假定執行字符集給出連續的值“ 0”至“ 9”,則使用“ 0”字符的值。 這是一個安全的假設,因為它由ISO C99草案的5.2.1.3規定:
在源基本字符集和執行基本字符集中,上述十進制數字列表中的每個0后面的字符的值應比前一個的值大1。
即,如果“ 0” == 48,則“ 1” == 49,依此類推。
如果只希望以str[k]
的字符串開頭的整數值,請使用運算符的地址:
a[k] = strtol(&str1[k],NULL,16);
如果需要使用十六進制數字,則可以假定執行字符集也按順序將“ a”編碼為“ f”,這是一個非常安全的假設(ASCII和unicode以及其他所有常見編碼都可以這樣做); 然后,您可以使用一個函數來測試值的范圍並根據該值進行賦值(如果介於“ 0”和“ 9”之間,則減去“ 0”,如果介於“ a”和“ f”之間,則減去“ a”)。 但是,如果您真的很偏執,可以創建一個查詢表:
char hexDigitLookup[256]; // The normal range of a char.
memset(hexDigitLookup, -1, 256);
hexDigitLookup['0'] = 0;
hexDigitLookup['1'] = 1;
hexDigitLookup['2'] = 2;
hexDigitLookup['3'] = 3;
hexDigitLookup['4'] = 4;
hexDigitLookup['5'] = 5;
hexDigitLookup['6'] = 6;
hexDigitLookup['7'] = 7;
hexDigitLookup['8'] = 8;
hexDigitLookup['9'] = 9;
hexDigitLookup['a'] = 10;
hexDigitLookup['b'] = 11;
hexDigitLookup['c'] = 12;
hexDigitLookup['d'] = 13;
hexDigitLookup['e'] = 14;
hexDigitLookup['f'] = 15;
因此,如果str[k]
是十六進制數字,則a[k] = hexDigitLookup[str1[k]]
將產生正確的值,否則將返回-1,而與執行字符集的布局方式無關。 當然,首先應該檢查str[k]
是否不小於0,例如在解析unicode時可能會小於0。 您可以改用(unsigned char)
。
atoi
需要一個字符串,因此可以使用char*
任何變體,請嘗試以下操作:
a[k] = atoi (str1+k);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.