C言語の文字列を数値に変換する方法を教えてください。

C言語では、文字列を整数に変換するライブラリ関数atoi()、浮動小数点数に変換するatof()を使用できます。これら2つの関数はどちらもstdlib.hヘッダファイルにあります。

atoi()関数を使用して

#include <stdlib.h>

int atoi(const char *str);

サンプルコード:

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

int main() {
    const char *str = "12345";
    int num = atoi(str);
    
    printf("The converted number is: %d\n", num);
    
    return 0;
}

atof()関数を用いる:

#include <stdlib.h>

double atof(const char *str);

ネイティブに日本語で言い換えてください、1つの選択肢のみで結構です:例:

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

int main() {
    const char *str = "3.14";
    double num = atof(str);
    
    printf("The converted number is: %f\n", num);
    
    return 0;
}

文字列が対応する数値型に変換できない場合は、atoi()、atof() 関数は 0 を返すので注意。実際の利用では文字列の形式が正しいことを確認するか、エラー処理を別途行う必要がある。

bannerAds