2023年2月11日星期六

C atoi 字串轉整數

 

atoi() — Calculate Integer Absolute Value

IBM 說明

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number. This character can be the null character that ends the string.

我的理解:此函式會將輸入的整數取決對值後回傳,字串的格式如果是符合下圖的,基本上都可以轉換。

(字串接受格式)

程式碼

  1. #include <string.h>
  2. #include <stdio.h>
  3. int main(void)
  4. {
  5. char *strnumber = " 123";
  6. int number_out;
  7. number_out = atoi(strnumber);
  8. printf("number_in:%s,number_out:%d\n", strnumber, number_out);
  9. strnumber = "-321";
  10. number_out = atoi(strnumber);
  11. printf("number_in:%s,number_out:%d\n", strnumber, number_out);
  12. }

執行結果


參考資料

https://www.ibm.com/docs/en/i/7.4?topic=functions-atoi-convert-character-string-integer


沒有留言:

發佈留言

打賞按讚