Sitemap
Tsungyu Yu

Tsungyu Yu

Ecole 42 的自我挑戰 — day03 — ex08(C)

2 min readNov 13, 2018

tl;dr: ASCII escape number

Press enter or click to view image in full size

第三天的第八題,這道題目將字串轉換成整數,而且要注意實際的atoi函式的模式。

Get Tsungyu Yu’s stories in your inbox

Join Medium for free to get updates from this writer.

實際的atoi函式會偵測正負號、格式符號、數字,當數字出現之後出現非數字時,函式停止並回傳整數,科學符號(e)與浮點(.)為非整數。

int ft_atoi(char *str)
{
long int r; //避免最大負數
short int sign; //修正正負號使用
r = 0;
while ((9 <= *str && *str <= 13) || *str == 32)
str++;
sign = (*str == '-') ? -1 : 1;
(*str == '+' || *str == '-') ? str++ : str;
while (*str && ('0' <= *str && *str <= '9'))
r = (r * 10) + *(str++) - '0';
return ((int)sign * (int)r);
}

測試時,我偷懶直接使用了ASCII代碼作為捷徑,意外的發現這件事情:

char c[] = "\40";    //如果使用反斜線時(\),ASCII代碼需要使用八進位作為轉
換。
char c[] = "\x20"; //如果要改16進位時,要後置x 如: \x代碼

以上。

--

--