C言語で文字列を数値に変換する方法
C 言語では、文字列を数値に変換するために atoi() や atof() 関数を使用できます。
- 文字列を整数に変換
int atoi(const char* str);
strは変換する文字列です。この関数は変換後整数として返します。文字列の中に数値以外の文字列があると変換は終了し、それまでに変換した整数値が返ります。
サンプルコード:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("转换后的整数为:%d\n", num);
return 0;
}
- 数値に変換
double atof(const char* str);
文字列strを浮動小数点数に変換し、変換後の浮動小数点数を返します。なお、atoi()関数と同様、文字列中に数値以外の文字が含まれると、それまでの変換結果が返り、変換は停止します。
native Japanese: コードの例
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14159";
double num = atof(str);
printf("转换后的浮点数为:%f\n", num);
return 0;
}