C 言語の文字列を数字に変換する方法は何ですか。
C言語では、文字列を数字に変換するために、標準ライブラリ関数であるatoi、atof、またはsscanfを使用することができます。
- アトイ
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "12345";
int num = atoi(str);
printf("The converted number is: %d\n", num);
return 0;
}
- 浮動小数点数に変換
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14";
float num = atof(str);
printf("The converted number is: %.2f\n", num);
return 0;
}
- sscanf関数
#include <stdio.h>
int main() {
char str[] = "The price is $12.50";
float price;
sscanf(str, "The price is $%f", &price);
printf("The converted number is: %.2f\n", price);
return 0;
}
以上の例では、文字列を整数に変換するためにatoi、浮動小数点数に変換するためにatof、および特定の形式の数字を抽出するためにsscanfが使用されています。