C语言でのatoi関数による文字列から整数の変換

C言語では、数値文字列を整数に変換するatoi関数を利用できます。atoi関数のプロトタイプは次のとおりです。

int atoi(const char *str);

atoi 関数は、文字列 str を整数型に変換して返します。具体的には以下のようになります。

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "12345";
    int num = atoi(str);
    printf("The converted integer is %d\n", num);
    return 0;
}

結果を出力

The converted integer is 12345

なお、atoi関数は文字列内の空白文字を無視し、文字列が整数に変換できない場合は0を返します。

bannerAds