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.

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

(字串接受格式)

程式碼

#include <string.h>
#include <stdio.h>

int main(void)
{
    char *strnumber = " 123";
    int number_out;

    number_out = atoi(strnumber);
    printf("number_in:%s,number_out:%d\n", strnumber, number_out);

    strnumber = "-321";
    number_out = atoi(strnumber);
    printf("number_in:%s,number_out:%d\n", strnumber, number_out);

}

執行結果


參考資料

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


沒有留言:

發佈留言

打賞按讚