用c语言将字符串转为数值
时间: 2024-01-01 07:04:18 浏览: 24
可以使用C语言 stdlib.h 库中的 atoi() 或 atof() 函数将字符串转为整数或浮点数。例如:
char str[] = "123";
int num = atoi(str); // 将字符串转为整数,num 的值为 123
char str[] = "3.14";
float num = atof(str); // 将字符串转为浮点数,num 的值为 3.14
相关问题
C++如何将字符串转为数值
C语言中可以使用函数库中的函数将字符串转为数值,例如:
1. atoi()函数:将字符串转为整数。
```c
#include <stdlib.h>
int atoi(const char *str);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "123";
char str2[] = "456.789";
int num1 = atoi(str1);
int num2 = atoi(str2);
printf("%d\n", num1); // 123
printf("%d\n", num2); // 456
return 0;
}
```
2. atof()函数:将字符串转为浮点数。
```c
#include <stdlib.h>
double atof(const char *str);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "123.456";
char str2[] = "789";
double num1 = atof(str1);
double num2 = atof(str2);
printf("%f\n", num1); // 123.456000
printf("%f\n", num2); // 789.000000
return 0;
}
```
3. strtol()函数:将字符串转为长整数。
```c
#include <stdlib.h>
long int strtol(const char *str, char **endptr, int base);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "123";
char str2[] = "0x1A";
char *endptr;
long int num1 = strtol(str1, &endptr, 10);
long int num2 = strtol(str2, &endptr, 16);
printf("%ld\n", num1); // 123
printf("%ld\n", num2); // 26
return 0;
}
```
4. strtod()函数:将字符串转为双精度浮点数。
```c
#include <stdlib.h>
double strtod(const char *str, char **endptr);
```
示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str1[] = "123.456";
char str2[] = "789";
char *endptr;
double num1 = strtod(str1, &endptr);
double num2 = strtod(str2, &endptr);
printf("%f\n", num1); // 123.456000
printf("%f\n", num2); // 789.000000
return 0;
}
```
C语言实现二进制字符串转为16进制字符串
可以通过将二进制字符串每四位分组,然后转换为对应的16进制数值,最终得到16进制字符串。以下是一个C语言实现的例子:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char binary[100];
printf("Enter a binary string: ");
scanf("%s", binary);
int len = strlen(binary);
int extra = len % 4;
if (extra > 0) {
// 如果二进制字符串长度不是4的倍数,则在前面添加0使其成为4的倍数
for (int i = 0; i < 4 - extra; i++) {
memmove(binary + 1, binary, len + 1);
binary[0] = '0';
len++;
}
}
int n = len / 4;
char hex[n + 1];
for (int i = 0; i < n; i++) {
int value = 0;
// 将四位二进制字符串转换为对应的数值
for (int j = 0; j < 4; j++) {
value = (value << 1) + (binary[i * 4 + j] - '0');
}
// 将数值转换为16进制字符
if (value < 10) {
hex[i] = '0' + value;
} else {
hex[i] = 'A' + value - 10;
}
}
hex[n] = '\0';
printf("The hex string is: %s\n", hex);
return 0;
}
```
示例运行结果:
```
Enter a binary string: 10110011010
The hex string is: 5B2
```