本質上,我有一條以兩個數字結尾的線。我可以閱讀數字,例如)“4”和“1”。我想將它們連接成“41”,然后將其讀取為值 41 的 int 型別。將單個字符轉換為 int 是直截了當的,但是這對兩個(或更多)字符如何作業?
我正在使用以下方法抓取字符:
int first_digit = ctoi(line[1]);
int second_digit = ctoi(line[2]);
其中 ctoi 定義為:
int ctoi( int c ) // https://stackoverflow.com/a/2279401/12229659
{
return c - '0';
}
uj5u.com熱心網友回復:
最簡單的方法是使用一個函式,例如sscanf(假設該行是一個正確的字串)
int num;
if (sscanf(line, "%d", &num) != 1) {
// handle conversion error
}
雖然,scanf通常不提供算術溢位保護,所以對于一個大數字它會失敗(你將無法跟蹤它)。
strtol和朋友們,當你超出范圍時會失敗(并會讓你知道)。
但是,您可以構建自己的函式,同樣沒有溢位保護:
#include <ctype.h>
#include <stdlib.h>
int stringToInt(char *str) {
int num = 0;
size_t start = (*str == '-') ? 1 : 0; // handle negative numbers
for (size_t i = start; str[i] != '\0'; i ) {
if (isdigit((unsigned char)str[i]) == 0) { // we have a non-digit
exit(1); // ideally you should set errno to EINVAL and return or terminate
}
num = (num * 10) (str[i] - '0');
}
return (start) ? -num : num;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523651.html
標籤:C字符级联获取线阿托伊
上一篇:指標的值改變而不修改
